[英]Comparing 2 elements of a 3x3 matrix to see if element 2 is adjacent to element 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;
}
但是,我可以通過編程方式執行此操作嗎? 有人知道這樣的算法嗎?
任何幫助表示贊賞。
假設矩陣的位置如下:
1 2 3
4 5 6
7 8 9
您應該能夠執行以下操作:
if ( abs(p2-p1) == 3 // test for vertical connectedness
|| ( abs(p2-p1) == 1 // test for horizontal connectedness
&& ( p1+p2 != 7 && p1+p2 != 13) ) ) // except for edge cases (3,4 and 6,7)
return true;
您還可以將網格上的每個零件轉換為坐標形式。
即:
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
我認為...? 尚未嘗試過。
不管網格大小如何,這都應該起作用。
假設這是JavaScript:
var N = 3; // size of matrix
var x1 = p1 % N, y1 = Math.floor(p1 / N);
var x2 = p2 % N, y2 = Math.floor(p2 / N);
return (x1 == x2 && Math.abs(y2 - y1) == 1) ||
(y1 == y2 && Math.abs(x2 - x1) == 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.