繁体   English   中英

比较3x3矩阵的2个元素以查看元素2是否与元素1相邻

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM