在二维数组中,如何检查两个元素是否共享垂直/对角线?

时间:2018-05-11 23:38:39

标签: javascript arrays indexing matching

 [[ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, %, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ %, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ]]

我有一个8x8'板'并想检查%符号是否在同一垂直线上。我知道如何检查它们是否在同一水平线上(在同一个阵列中),但我无法弄清楚如何检查对角线和垂直线。

这是我的完整代码:

var whiteQueen = [2, 5];
var blackQueen = [5, 0];
var danger = false;

var board =
[
  [0, 1, 2, 3, 4, 5, 6, 7],
  [1, 1, 2, 3, 4, 5, 6, 7],
  [2, 1, 2, 3, 4, 5, 6, 7],
  [3, 1, 2, 3, 4, 5, 6, 7],
  [4, 1, 2, 3, 4, 5, 6, 7],
  [5, 1, 2, 3, 4, 5, 6, 7],
  [6, 1, 2, 3, 4, 5, 6, 7],
  [7, 1, 2, 3, 4, 5, 6, 7]
];


for (i = 0; i < 8; i++) { //plot white queen
  if (whiteQueen[0] === i) {
    for (j = 0; j < 8; j ++) {
      if (whiteQueen[1] === j) {
        board[i][j] = 'x';
      }
    } 
  }
}

for (i = 0; i < 8; i++) { //plot black queen
  if (blackQueen[0] === i) {
    for (j = 0; j < 8; j ++) {
      if (blackQueen[1] === j) {
        board[i][j] = 'x';
      }
    }
  } 
}

for (i = 0; i < 8; i++) { //reset board number guide
  for (j = 0; j < 8; j++) {
    if (typeof board[i][j] == 'number') {
     board[i][j] = 0;
    }
  }
} 

for (i = 0; i < 8; i++) { //re-plot queens
  for (j = 0; j < 8; j++) {
    if (board[i][j] === 'x') {
      board[i][j] = 1;
    }
  }
}

for (i = 0; i < 8; i++) {
  var sameLineCount = 0;
  for (x = 0; x < 8; x++) {
    if (board[i][x] == 'x') { 
      if () // no idea how to register a matching line/diagonal
      sameLineCount += 1;
    } 
  }
}

/*[ [ 0, 0, 0, 0, 0, 0, 0, 0 ],
    [ 0, 0, 0, 0, 0, 0, 0, 0 ],
    [ 0, 0, 0, 0, 0, 1, 0, 0 ],
    [ 0, 0, 0, 0, 0, 0, 0, 0 ],
    [ 0, 0, 0, 0, 0, 0, 0, 0 ],
    [ 1, 0, 0, 0, 0, 0, 0, 0 ],
    [ 0, 0, 0, 0, 0, 0, 0, 0 ],
    [ 0, 0, 0, 0, 0, 0, 0, 0 ] ]*/

所以基本上它是一个国际象棋棋盘,我采取一系列坐标并检查其中一个皇后是否有危险。我对所有for循环感到困惑,而且我不确定我是否会以正确的方式解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以获得您正在寻找的2个标志的位置并查看:

  

如果(x1 == x2)则它们在同一水平线上

     

如果(y1 == y2)则它们在同一垂直线上

     

if(| x1 - x2 | == | y1 - y2 |)然后它们在同一个Diagonal上