我已經開始一個項目,試圖創建一個Ken Ken難題。如果你不確定Ken Ken是什麼,它就像Sudoku一樣,在行或列中不能有重複的整數值。用隨機數字填充二維數組
我正在嘗試使用爲每個新行創建的數組列表中的數字填充二維數組。我將檢查數組列表中的數字是否與其自己的行和列中的數字不匹配。
當我運行我的代碼時,當我嘗試從列表中刪除整數值時,出現「Index Out Of Bounds」異常。我不知道爲什麼會發生這種情況,因爲我認爲我得到了正確的因素。
這裏是我的代碼:
int GRID_SIZE = 4;
int[][] grid = new int[GRID_SIZE][GRID_SIZE];
List<Integer> nums = new ArrayList<Integer>();
private void populateGrid() {
for (int row = 0; row < GRID_SIZE; row ++) {
// Creates an array of values from 1 to grid size.
for (int i = 1; i <= GRID_SIZE; i++) nums.add(i);
for (int col = 0; col < GRID_SIZE; col++) {
while (nums.size() > 0) {
// Gets a random number from the Array List
int ranNum = nums.get(numGen.nextInt(GRID_SIZE));
// Checks to see if the number is placeable.
if (canPlace(ranNum, row, col)) {
// Places the number in the 2D Array
grid[row][col] = ranNum;
break;
} else {
// Removes duplicate element from the Array List.
nums.remove(ranNum); <------{Index Out Of Bounds Exception]
}
}
}
}
}
private boolean canPlace(int ranNum, int row, int col) {
for (int i = 0; i < GRID_SIZE; i++) {
// Checks if the specified number is already in the row/column.
if (grid[col][i] == ranNum) return false;
if (grid[i][row] == ranNum) return false;
}
return true;
}
我有這幾個問題:
首先,爲什麼我得到錯誤我是?
其次還有什麼更好的比一個二維數組,網格和我把我的號碼方式使用?
最後,上午我正在使用中斷?
在此先感謝您的答案。
這似乎錯在第二個for循環:'我<= GRID_SIZE'您正在使用什麼確切的數據類型來存儲隨機數一覽表 – Keppil 2012-07-29 22:21:58
?如果它是一個列表,那麼當你刪除東西時它可能會縮小,所以如果你的列表有9個,並且你找到一個並刪除它,那麼它現在有8個。如果你再次查看第9個位置,這是一個超出界限例外 – 2012-07-29 22:22:42
我真的不知道從哪裏開始。即使小問題得到解決,您的整個方法似乎都是錯誤的,並且無法解決最棘手的問題。你需要回溯。 – 2012-07-29 22:22:54