【发布时间】:2012-07-27 15:31:40
【问题描述】:
我已经开始了一个项目,试图创建一个 Ken Ken 拼图。如果您不确定 Ken Ken 是什么,它与数独类似,在行或列中不能有重复的整数值。
我正在尝试使用为每个新行创建的数组列表中的数字填充二维数组。我会检查从数组列表中获取的数字是否与它自己的行和列中的任何数字不匹配。
当我运行我的代码时,当我尝试从列表中删除整数值时出现“索引超出范围”异常。我不确定为什么会发生这种情况,因为我认为我得到了正确的元素。
这是我的代码:
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 循环中似乎是错误的:
i <= GRID_SIZE -
您使用什么确切的数据类型来存储随机数列表?如果它是一个列表,它可能会随着你删除东西而缩小,所以如果你的列表有 9 个,并且你找到一个并删除它,它现在有 8 个。如果你再次尝试查看第 9 个位置,这是一个越界异常
-
我真的不知道从哪里开始。即使小问题得到解决,你的整个方法似乎都是错误的,无法解决最困难的问题。你需要有回溯。
-
是的,
nums声明的尺寸是否与grid相同?另外,请指出您获得IndexOutOfBoundsException的行。 -
@Keppil 谢谢你,我想我也是从 0 而不是 1 开始的。我现在已经改变了。
标签: java arrays random sudoku latin-square