gpt4 book ai didi

c++ - 获取数独 block 的坐标

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:20 25 4
gpt4 key购买 nike

所以我尝试解决一个问题,我需要在给定数独网格中的单元格的情况下获取数独 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],该函数应该返回 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);

}

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

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

谢谢。

最佳答案

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

关于c++ - 获取数独 block 的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47158033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com