获取数独块的坐标

时间:2017-11-07 12:28:56

标签: c++ algorithm multidimensional-array range sudoku

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

例如,鉴于此委员会:

 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],则该函数应返回0-2表示x值,0-2表示y值。 对于[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);

    }

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

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

感谢。

1 个答案:

答案 0 :(得分:2)

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