我不太確定爲什麼我得到一個數組索引超出界限的例外。據我的理解,我的double數組的大小爲3,所以索引從0 - 2。在我的isSolvable方法中,我嘗試計算我的double數組中反轉的數目,其中反轉是任何一對塊i和j,其中我在考慮董事會的主要次序時出現在j之後。我嘗試通過將我的2d數組轉換爲1d數組來完成此操作,以便遍歷1d數組來計算所有的反轉。如果反轉是偶數的(在奇數尺寸的棋盤內),那麼8拼圖棋盤就可以解決。我的for循環只能計算數組的長度,所以我不完全確定我是如何得到數組索引超出範圍的異常。數組索引超出範圍 - 將2d轉換爲1d
在此先感謝!每個答案都有助於並阻止我在將來犯同樣的錯誤。
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
}
非常感謝! – cannotcompute 2014-10-08 19:53:33