我不太确定为什么会出现数组索引越界异常。据我了解,我的双精度数组的大小为 3,因此索引从 0 到 2。在我的 isSolvable 方法中,我尝试计算我的双精度数组中的反转数,其中反转是任何一对块 i 和 j,其中i < j 但在以行优先顺序考虑董事会时, i 出现在 j 之后。我尝试通过将我的二维数组转换为一维数组来做到这一点,这样我就可以遍历一维数组来计算所有的反转。如果反转是偶数(在奇数大小的板上),则 8 拼图板是可解的。我的 for 循环只计算到数组的长度,所以我不完全确定我是如何得到一个 Array Index Out Of Bounds 异常的。
提前致谢!每个答案都有助于并防止我在未来犯同样的错误。
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
}