java - Array index out of bounds - 2d to 1d -
i working algs4 8-puzzle program presented princeton. getting array index out of bounds exception in second loop. see issue throwing exception? board class + relevant method looks this:
public class board { private final int[][] blocks; private final int n; // construct board n-by-n array of blocks // (where blocks[i][j] = block in row i, column j) public board(int[][] blocks){ n = blocks.length; this.blocks = new int[n][]; (int i=0; i<n; i++){ this.blocks[i] = arrays.copyof(blocks[i], n); } } // board dimension n public int dimension(){ return this.n; } //is board solvable? public boolean issolvable(){ int inversions = 0; list<integer> convert = new arraylist<>(); // convert 2d 1d (int = 0; < blocks.length; i++){ (int j = 0; j < blocks[i].length; j++){ convert.add(blocks[i][j]); } } (int = 0; < blocks.length; i++){ //counts number of inversions if (convert.get(i) < convert.get(i-1)){ //arrayindexoutofbounds -1 inversions++; } } if (inversions % 2 == 0){ return true; //even } return false; //odd }
convert.get(i-1)
out of bounds when i==0.
you should change start index of loop :
(int = 1; < blocks.length; i++){ //counts number of inversions if (convert.get(i) < convert.get(i-1)){ inversions++; } }
Comments
Post a Comment