获取数独块的坐标

Getting the coordinates of a sudoku block

本文关键字:坐标 获取      更新时间:2023-10-16

所以我试图解决一个问题,我需要从数独网格中获取一个数独块的起点。

例如,给定此板:

 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],则该函数应为 x 值返回 0-2,为 y 值返回 0-2。对于 [0,3],对于 x 值的范围,它应该返回 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);
    }

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

有没有更好的方法?如果是这样,有人可以推荐/告诉我一种方法吗?

谢谢。

让我们定义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]