比较 3x3 矩阵的 2 个元素,查看元素 2 是否与元素 1 相邻
基本上,我正在创建一个可以交换碎片的拼图。我想确保交换 2 个元素时,选择是有效的。
由于拼图只有 9 块 (3x3),我目前正在使用代码:
function valid_selection(p1, p2) {
if (p1 == 1 && (p2 == 2 || p2 == 4)) return true;
if (p1 == 2 && (p2 == 1 || p2 == 3 || p2 == 5)) return true;
if (p1 == 3 && (p2 == 2 || p2 == 6)) return true;
if (p1 == 4 && (p2 == 1 || p2 == 5 || p2 == 7)) return true;
if (p1 == 5 && (p2 == 2 || p2 == 4 || p2 == 6 || p2 == 8)) return true;
if (p1 == 6 && (p2 == 3 || p2 == 5 || p2 == 9)) return true;
if (p1 == 7 && (p2 == 4 || p2 == 8)) return true;
if (p1 == 8 && (p2 == 5 || p2 == 7 || p2 == 9)) return true;
if (p1 == 9 && (p2 == 6 || p2 == 8)) return true;
return false;
}
但是,我可以通过编程来完成此操作吗?有人知道这样的算法吗?
任何帮助表示赞赏。
Basically, I'm creating a puzzle where you can swap pieces. And I want to make sure that when swapping 2 elements, the selection is valid.
Since the puzzle is only 9 pieces (3x3), I am currently using the code:
function valid_selection(p1, p2) {
if (p1 == 1 && (p2 == 2 || p2 == 4)) return true;
if (p1 == 2 && (p2 == 1 || p2 == 3 || p2 == 5)) return true;
if (p1 == 3 && (p2 == 2 || p2 == 6)) return true;
if (p1 == 4 && (p2 == 1 || p2 == 5 || p2 == 7)) return true;
if (p1 == 5 && (p2 == 2 || p2 == 4 || p2 == 6 || p2 == 8)) return true;
if (p1 == 6 && (p2 == 3 || p2 == 5 || p2 == 9)) return true;
if (p1 == 7 && (p2 == 4 || p2 == 8)) return true;
if (p1 == 8 && (p2 == 5 || p2 == 7 || p2 == 9)) return true;
if (p1 == 9 && (p2 == 6 || p2 == 8)) return true;
return false;
}
But, can I do this programatically? Anyone know of such an algorithm?
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您的矩阵具有如下位置:
您应该能够执行以下操作:
Assuming your matrix has positions like so:
You should be able to do the following:
您还可以将网格上的每个部分转换为坐标形式。
即:
1是(0,0),
2 是 (0,1),
3是(0,2),
4 是 (1,0),
等等
因此,假设 p1 的坐标是 (x_p1, y_p1) 且 p2 是 (x_p2, y_p2) 那么你的函数将返回 true 如果:
( abs(x_p2 - x_p1) + abs(y_p2 - y_p1) ) == 1
I思考...?还没有实际尝试过。
无论网格大小如何,这都应该有效。
You could also convert each piece on the grid into coordinate form.
ie:
1 is (0,0),
2 is (0,1),
3 is (0,2),
4 is (1,0),
etc
So, given that the coordinate of p1 is (x_p1, y_p1) and p2 is (x_p2, y_p2) then your function would return true if:
( abs(x_p2 - x_p1) + abs(y_p2 - y_p1) ) == 1
I think...? Haven't actually tried it.
And this should work regardless of grid size.
假设这是 JavaScript:
Assuming this is JavaScript: