我最近开始实现一个数独解算器,它是在算法x的帮助下完成的,这意味着对于给定的数独,有一个包含许多不同可能解的覆盖矩阵,算法的任务是找到正确的解。
但问题出在矩阵的生成器上我会尽量简化这个问题。我正在使用一个封面矩阵,帮助我解决数独矩阵中的每一行都是唯一的条目为了组成一行,我们需要确定数独中给定的数字在哪个单元格、行、列和框中。
由于数独维度是由内部框的维度定义的(如下图所示),所以我使用这些维度来确定pregiven数字在哪一行和哪一列中。
每一个盒子都有一个宽度和高度的尺寸,或者如果你喜欢m和n或者任何其他符号-经典的9x9数独有一个m=3和n=3(内盒子的尺寸)。
java - 确定Sudoku中数字在哪个方框中的一种方法是-LMLPHP
如你所见,这是一个自定义数独,尺寸为m=2和n=3,有6个盒子。
我有一个问题,创建一个公式,将给我的信息框中的数字是。所以基本上输入应该是数独中数字的位置(索引),输出应该是数字所在的框的编号。
下面是我到目前为止尝试优化的代码,但它仍然不能非常正确地计算索引我使用了给定数字所在行的索引,并尝试使用该索引来确定列的索引,并尝试将二者结合起来确定框的编号。请告诉我我在哪里犯了错误。

     public static void assignSudokuBox(int rowIndex, int m, int n){

     double x = Math.ceil(Math.ceil((rowIndex+1)*1.0/(m*n))/m);

     double columnIndex = (rowIndex%(m*n))*m*n + (rowIndex/(m*n));

     double y = Math.ceil(Math.ceil(columnIndex*1.0/(m*n))/n);

     double number = Math.ceil((x-1)*m+y);

     System.out.println("Box of index " + rowIndex + " is: " + number + ".");

 }

最佳答案

假设基于0的索引和框的编号方式与单元格相同,则可以按如下方式计算值:

public static void assignSudokuBox(int rowIndex, int m, int n) {
    // index, if devided to pieces n x 1
    int nChunkIndex = rowIndex / n;

    // every row has m of those pieces and there are m rows in each box
    int row = nChunkIndex / (m*m);

    int column = nChunkIndex % m;

    int result = column + row * m;

    System.out.println("Box of index " + rowIndex + " is: " + result + ".");

}

输出
for (int i = 0; i < 36; i++) {
    assignSudokuBox(i, 2, 3);
}

Box of index 0 is: 0.
Box of index 1 is: 0.
Box of index 2 is: 0.
Box of index 3 is: 1.
Box of index 4 is: 1.
Box of index 5 is: 1.
Box of index 6 is: 0.
Box of index 7 is: 0.
Box of index 8 is: 0.
Box of index 9 is: 1.
Box of index 10 is: 1.
Box of index 11 is: 1.
Box of index 12 is: 2.
Box of index 13 is: 2.
Box of index 14 is: 2.
Box of index 15 is: 3.
Box of index 16 is: 3.
Box of index 17 is: 3.
Box of index 18 is: 2.
Box of index 19 is: 2.
Box of index 20 is: 2.
Box of index 21 is: 3.
Box of index 22 is: 3.
Box of index 23 is: 3.
Box of index 24 is: 4.
Box of index 25 is: 4.
Box of index 26 is: 4.
Box of index 27 is: 5.
Box of index 28 is: 5.
Box of index 29 is: 5.
Box of index 30 is: 4.
Box of index 31 is: 4.
Box of index 32 is: 4.
Box of index 33 is: 5.
Box of index 34 is: 5.
Box of index 35 is: 5.

关于java - 确定Sudoku中数字在哪个方框中的一种方法是,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38637909/

10-17 03:13