给定2D数组行/列索引,如何制定数独“子网格”索引?

时间:2014-03-10 21:19:35

标签: java arrays algorithm math sudoku

我正在用Java实现一个Sudoku网格,而我最不能做的就是将下面的逻辑简化为一个数学公式。

这是对此问题的跟进:How to get the Sudoku 2D-array index, given its "sub-grid" and "cell-in-the-sub-grid" indexes?

这是功能,效果很好:

public static final int getGridIndexForCell(int rowIdx_0to8, int colIdx_0to8)  {
   int idx = -1;
   if(rowIdx_0to8 < 3)  {
      //Grid-row 1
      idx = ((colIdx_0to8 < 3) ? 0
          : ((colIdx_0to8 < 6) ? 1 : 2));

   }  else  if(rowIdx_0to8 < 6)  {
      //Grid-row 2
      idx = ((colIdx_0to8 < 3) ? 3
          : ((colIdx_0to8 < 6) ? 4 : 5));

   }  else  {
      //Grid-row 3
      idx = ((colIdx_0to8 < 3) ? 6
          : ((colIdx_0to8 < 6) ? 7 : 8));
   }
   return  idx;
}

它返回“网格索引”,基于提供的基础二维数组的行和列索引。

这就是我对网格的意思(我将整个事情称为“电路板”):

        |         |
   0    |    1    |    2
        |         |
 -------------------------
        |         |
   3    |    4    |    5
        |         |
 -------------------------
        |         |
   6    |    7    |    8
        |         |

每个网格有九个单元格,索引如下

0 1 2
3 4 5
6 7 8

我很感激注释的答案,尽可能多,因为这是我还没有得到的。

3 个答案:

答案 0 :(得分:2)

所以你想要的公式是

grid_index = (column / 3) + (row / 3) * 3 = column / 3 + row - row % 3

grid_index3列增长一grid_index,每3 row增长3 {{1}}增长{{1}} 。所有除法都用整数完成。

答案 1 :(得分:1)

你想要的是

return (rowIdx_0to8  / 3)* 3 + (colIdx_0to8 / 3)

对于rowIndex_0to8 = 7,colIdx_0to8 = 6
第7/3行= 2 * 3 = 6
列+ 5/3 = 1
index = 7

答案 2 :(得分:1)

public static void f( int rowIdx_0to8, int colIdx_0to8) {
        System.out.println( 3 * Math.floor( rowIdx_0to8 / 3) +
                                                 Math.floor( colIdx_0to8 / 3));
}

甚至更简单:

public static void f( int rowIdx_0to8, int colIdx_0to8) {
        System.out.println( 3 * ( rowIdx_0to8 / 3) + ( colIdx_0to8 / 3));
}

online example

相关问题