0

I'm not really sure as to why I'm getting an Array Index Out Of Bounds Exception. To my understanding, my double array is of size 3, so the index goes from 0 - 2. In my isSolvable method I try to count the number of inversions within my double array, where an inversion is any pair of blocks i and j where i < j but i appears after j when considering the board in row-major order. I try to do this by converting my 2d array to a 1d array so that I could traverse through the 1d array to count up all the inversions. If the inversions are even (within a board of odd numbered size) then the 8 puzzle board is solvable. My for loops only count up to the length of the array, so I'm not entirely sure how I'm getting an Array Index Out Of Bounds exception.

Thanks in advance! Every answer helps and prevents me from making the same mistakes in the future.

int N = 3; 
static int [][] copy; 

//construct a board from an N-by-N array of blocks 
//(where blocks[i][j] = block in row i, column j) 
public Board(int[][] blocks){
    blocks =  new int[N][N]; //creates array of size N

    //generates random numbers 0 inclusive to # exclusive 
    //creates ArrayList - shuffle used to prevent repeating of numbers 
    List<Integer> randomList = new ArrayList<>(); 
    for (int i = 0; i < 9; i++){
        randomList.add(i); 
    }
    int counter = 0; 
    Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomList.get(counter); 
            counter++;
        }
    }
    copy = blocks.clone(); 
}


 //is the board solvable? 
 public boolean isSolvable(){
    int inversions = 0; 
    List<Integer> convert = new ArrayList<>(); // used to convert 2d to 1d 
    for (int i = 0; i < copy.length; i++){
        for (int j = 0; i < copy[i].length; j++){
            convert.add(copy[i][j]); //ARRAYINDEXOUTOFBOUNDSEXCEPTION: 3 
        }
    }
    for (int i = 0; i < copy.length; i++){ //counts the number of inversions 
        if (convert.get(i) < convert.get(i-1)){
            inversions++; 
        }
    }
    if (inversions % 2 == 0){
        return true; //even 
    }
    return false; //odd 
}

//unit test 
public static void main(String[] args){
    //prints out board 
    printArray(); 
    Board unittest = new Board(copy); 
    unittest.isSolvable(); //ARRAYINDEXOUTOFBOUNDSEXCEPTION: 3 



}

2 Answers2

4

You have a typo in the inner loop of isSolvable:

for (int j = 0; i < copy[i].length; j++){
                ^
                |
           should be j

should be:

for (int j = 0; j < copy[i].length; j++){
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Array index j is going out of bound since you are continuously increment value of j while checking i < copy[i].length. Since this value remains true j is incremented to a number which is an index out of bound for array copy[i][j].

Murtaza Zaidi
  • 599
  • 3
  • 14