获取数独块的坐标
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],则该函数应为 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]
。
相关文章:
- 如何在C++中获取坐标?
- 使用 GTK3 C++获取指针坐标
- 从 CGAL 3D 网格生成中获取顶点坐标的 -6.27744e+66:mesh_implicit_sphere示例
- 如何从 3d 对象文件中获取 3d 坐标
- 从 3 个视点在 3 张图像上有 3 个点如何在 3D 空间中获取其坐标?
- 如何从 DirectXTK (ToolKit) DirectX::Model 类获取所有顶点坐标以用于冲突检测
- 获取具有X,Y和距离的OPENCV中的3D坐标
- 获取QImage像素坐标
- OpenCV从2D像素获取3D坐标
- 如何通过调用 gluUnproject 两次(不使用 gluUnProject)从场景坐标中获取深度值
- 获取数独块的坐标
- 在调整大小窗口时,如何使用鼠标单击来获取图像的坐标
- 将圆圈分为n相等的部分,以获取每个分界点的坐标
- 从卫星的ECI坐标获取地球上的纬度和经度点
- Android NDK-如何从TAP中获取坐标并将其显示在文本视图上
- OpenGL获取离当前鼠标位置最近的世界三维点的三维坐标
- 当用户按 Ctrl 并单击时获取鼠标坐标
- 获取RGBDemo的鼠标位置坐标
- D3D:如何从 x,y 坐标获取颜色
- 在c++中通过坐标获取png