我正在研究一个数独的东西,我在减少它的一部分时遇到了麻烦。
我正在设计一个SudokuBoard
对象,以拥有一个底层的2D字节数组,以及该数组的三个不同视图:行单元,列单元和网格单元。网格是九乘九块,索引如下:
GRID INDEX
| |
0 | 1 | 2
| |
-------------------------
| |
3 | 4 | 5
| |
-------------------------
| |
6 | 7 | 8
| |
每个网格有九个单元格,索引如下
CELL INDEX
0 1 2
3 4 5
6 7 8
这是电路板的2d阵列坐标:
2D-ARRAY COORDINATE
[0,0] [0,1] [0,2] | [0,3] [0,4] [0,5] | [0,6] [0,7] [0,8]
[1,0] [1,1] [1,2] | [1,3] [1,4] [1,5] | [1,6] [1,7] [1,8]
[2,0] [2,1] [2,2] | [2,3] [2,4] [2,5] | [2,6] [2,7] [2,8]
-------------------+---------------------+-------------------
[3,0] [3,1] [3,2] | [3,3] [3,4] [3,5] | [3,6] [3,7] [3,8]
[4,0] [4,1] [4,2] | [4,3] [4,4] [4,5] | [4,6] [4,7] [4,8]
[5,0] [5,1] [5,2] | [5,3] [5,4] [5,5] | [5,6] [5,7] [5,8]
-------------------+---------------------+-------------------
[6,0] [6,1] [6,2] | [6,3] [6,4] [6,5] | [6,6] [6,7] [6,8]
[7,0] [7,1] [7,2] | [7,3] [7,4] [7,5] | [7,6] [7,7] [7,8]
[8,0] [8,1] [8,2] | [8,3] [8,4] [8,5] | [8,6] [8,7] [8,8]
我已经创建了一个函数来获取数组坐标,给定网格和单元格索引。确定列索引是一个大脑破坏者,但我认为它是
int colIdx = (cell_idx % 3) + ((grid_idx % 3) * 3);
我也想出确定行索引,但我对这有多复杂感到不满。
int rowIdx = -1;
if(grid_idx < 3) {
rowIdx = ((cell_idx < 3) ? 0
: ((cell_idx < 6) ? 1 : 2));
} else if(grid_idx < 6) {
rowIdx = ((cell_idx < 3) ? 3
: ((cell_idx < 6) ? 4 : 5));
} else {
rowIdx = ((cell_idx < 3) ? 6
: ((cell_idx < 6) ? 7 : 8));
}
如果有人有关于如何减少这种情况的想法,理想情况下是一个数学公式,我会很感激。
这是一个展示它的工作应用程序。谢谢你的帮助。
import java.util.Arrays;
/**
<P>{@code SudokuGridUnitCoordinates}</P>
**/
public class SudokuGridUnitCoordinates {
public static final void main(String[] idxZeroGridIdx_0to8) {
int gridIdx = -1;
try {
gridIdx = Integer.parseInt(idxZeroGridIdx_0to8[0]);
if(gridIdx < 0 || gridIdx > 8) {
throw new IllegalArgumentException();
}
} catch(IllegalArgumentException | ArrayIndexOutOfBoundsException x) {
throw new IllegalArgumentException("The first element in idxZeroGridIdx_0to8 must be a digit zero through 8: " + Arrays.toString(idxZeroGridIdx_0to8));
}
printCellCoordinates(gridIdx, 0);
printCellCoordinates(gridIdx, 1);
printCellCoordinates(gridIdx, 2);
printCellCoordinates(gridIdx, 3);
printCellCoordinates(gridIdx, 4);
printCellCoordinates(gridIdx, 5);
printCellCoordinates(gridIdx, 6);
printCellCoordinates(gridIdx, 7);
printCellCoordinates(gridIdx, 8);
}
private static final void printCellCoordinates(int grid_idx, int cell_idx) {
int rowIdx = -1;
if(grid_idx < 3) {
rowIdx = ((cell_idx < 3) ? 0
: ((cell_idx < 6) ? 1 : 2));
} else if(grid_idx < 6) {
rowIdx = ((cell_idx < 3) ? 3
: ((cell_idx < 6) ? 4 : 5));
} else {
rowIdx = ((cell_idx < 3) ? 6
: ((cell_idx < 6) ? 7 : 8));
}
int colIdx = (cell_idx % 3) + ((grid_idx % 3) * 3);
System.out.println("grid=" + grid_idx + ", cell=" + cell_idx + " --> sudoku2DGridArray[" + rowIdx + ", " + colIdx + "]");
}
}
答案 0 :(得分:3)
所有?:
运算符的块只是grid_idx - grid_idx % 3 + cell_idx / 3
答案 1 :(得分:3)
怎么样?
rowIdx = 3*(grid_idx/3) + cell_idx/3
所有除法都是整数除法