[英]Filling a 2D array with randomised numbers
我已经开始尝试创建Ken Ken拼图。 如果你不确定Ken Ken是什么,它就像Sudoku一样,行或列中没有重复的整数值。
我正在尝试使用为每个新行创建的数组列表中的数字填充2D数组。 我进行检查以查看从数组列表中获取的数字是否与其自己的行和列中的任何数字都不匹配。
当我运行我的代码时,当我尝试从列表中删除整数值时,我得到一个“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;
}
我有几个问题:
首先, 为什么我得到的错误是我 ?
其次,对于网格和我放置数字的方式,有什么比2D数组更好用吗?
最后, 我正确使用了休息吗?
提前感谢您的回答。
由于List
API中的失败(IMO)而发生IndexOutOFBoundsException
。 它有一个remove(Object element)
方法,它是你想要调用的方法,还有一个remove(int index)
方法,这是你实际调用的方法。 后者试图删除给定索引处的元素,因为您的参数可能大于列表大小。 您可以将ranNum
变量ranNum
转换为Integer
或Object
,以确保调用正确的方法。
for (int i = 0; i <= GRID_SIZE; i++) nums.add(i);
这对我来说没什么意义。 你正在添加0-4的数字。 数组中只有索引最多3个。 0-1-2-3 ...
没有真正看到更多的代码,或者确切地知道你的索引在哪里超出界限......这是一个黑暗的镜头。
如何解决问题的方法呢? 从有效的方块开始并对其进行转换。 这两个操作“交换两行”和“交换两列”保留了广场的属性。 这允许你做两个Fisher-Yates shuffle,一个在行上,一个在列上,只要你从一个有效的方块开始就可以给你一个有效的随机方块。 构造一个初始有效方是微不足道的:
123456
234561
345612
456123
561234
612345
在仔细查看我的代码后,我意识到我的主要错误是使用canPlace(int ranNum, int row, int col)
方法。
我所做的就是交换col
和row
值并且它有效。
感谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.