我已经开始尝试创建Ken Ken拼图的项目.如果不确定Ken Ken是什么,则它与Sudoku相似,即行或列中不能有重复的整数值.
我试图用为每个新行创建的数组列表中的数字填充2D数组.我进行检查以查看从“数组列表”中获取的数字是否与其自己的行和列中的任何数字都不匹配.
当我运行代码时,当我尝试从列表中删除整数值时,出现“索引越界”异常.我不确定为什么会这样,因为我认为我得到了正确的要素.
这是我的代码:
int GRID_SIZE = 4;
int [] [] grid =新的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);
}
}
}
}
}
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;
}
我对此有一些疑问:
首先,为什么我会得到我自己的错误?
其次,还有什么比二维数组更适合使用网格以及我放置数字的方式呢?
最后,我是否正确使用休息时间?
预先感谢您的回答.