我已经开始一个项目,试图创建一个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