获取数独块的坐标

Getting the coordinates of a sudoku block

所以我尝试解决一个问题,我需要在给定数独网格中的单元格的情况下获取数独块的起点。

例如给定这个板:

 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]

假设 [y,x]

如果给定的单元格是 [1,1],函数应该 return x 值的 0-2 和 y 值的 0-2。 对于 [0,3],x 值的范围应为 return 3-5,y 值的范围应为 0-2。

这是我写的函数:

std::pair<int, int> getBlock(const double val) const {
        double ourBlock = ceil(val / sqrt(size));
        int blockSize = sqrt(size);
        int currBlock = 1;
        int ourBlkStrt = 0;
        for (int i = 0; i < size; i++) {
            if (currBlock == ourBlock) {
                if (currBlock > 1) {
                    ourBlkStrt = i + blockSize;
                } else {
                    ourBlkStrt = i;
                }
                break;
            } else {
                if (i % blockSize == 0) {
                    currBlock++;
                }
            }
        }
        int ourBlkEnd = 0;
        if (ourBlkStrt != 1) {
        ourBlkEnd = ourBlkStrt + (blockSize);
    } else {
        ourBlkEnd = ourBlkStrt + (blockSize -1);
    }

        return std::pair<int, int>(ourBlkStrt, ourBlkEnd);

    }

我的代码并不是最好的方法。它在大多数情况下都有效,但有时它会给我一个超出要求范围的值。

有更好的方法吗?如果是这样,有人可以 recommend/show 给我一个方法吗?

谢谢。

让我们定义f:

std::pair<unsigned, unsigned> f(unsigned cell_index)
{
    const unsigned block_index = cell_index / 3;
    const unsigned lowest_block_index = block_index * 3;
    const unsigned highest_block_index = (block_index+1) * 3 - 1;
    return { lowest_block_index, highest_block_index };
}

std::pair<unsigned, unsigned> f(unsigned cell_index)
{
    switch (cell_index)
    {
       case 0: return { 0, 2 };
       case 1: return { 3, 5 };
       case 2: return { 6, 8 };
     }
     return { -1, -1 };
}

您可以检查:

f(0) == { 0, 2 };
f(1) == { 3, 5 };
f(2) == { 6, 8 };

那么,设计为[y, x]的单元格的范围是[f(y).first, f(x).first]--[f(y).second, f(x).second]