我有一个 9x9 数独网格,我需要从网格中的每个 3x3 方 block 中获取一个随机数。
最糟糕的代码是这样的:
if(square == 0) {
row = random.nextInt(3);
col = random.nextInt(3);
}
if(square == 1) {
row = random.nextInt(3);
col = random.nextInt(3) + 3;
}
if(square == 2) {
row = random.nextInt(3);
col = random.nextInt(3) + 6;
}
if(square == 3) {
row = random.nextInt(3) + 3;
col = random.nextInt(3);
}
if(square == 4) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 3;
}
if(square == 5) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 6;
}
if(square == 6) {
row = random.nextInt(3) + 6;
col = random.nextInt(3);
}
if(square == 7) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 3;
}
if(square == 8) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 6;
}
其中 square
是网格中正方形的索引 (square
= 0,1,...,8)
我不知道如何以更好的方式编写它。
一些想法?谢谢
最佳答案
这应该适用于任何正方形尺寸。在你的例子中是 3x3,所以大小是 3。
int size = 3;
row = random.nextInt(size) + (square / size) * size;
col = random.nextInt(size) + (square % size) * size;
关于Java - 从 9x9 网格中的每个方格中选择一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669358/