【问题标题】:Is there a way to identify if an array matches with each set in the 2d array after looping through a 2d array for each element in an array?在遍历数组中每个元素的二维数组后,有没有办法确定数组是否与二维数组中的每个集合匹配?
【发布时间】:2018-12-20 01:53:52
【问题描述】:

我正在创建一个 tictactoe 游戏,并尝试将 winPattern 2d 数组中的每个集合数组与 placePieces 数组进行比较。

我已经创建了循环来遍历每个 placePieces 数组的 winPattern 二维数组,但是因为它不会将每个数组识别为一个集合,而是简单地遍历各个值,所以它不能按预期工作。

const winPattern = [
        //horizontal
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],

        //vertical
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],

        //diagonal
        [0, 4, 8],
        [2, 4, 6]
  ];
//positions that o or x would be in tictactoe
const placePieces = [0, 1, 2, 4, 8];
let count = 0;

nextPiece:
for (let i = 0; i < placePieces.length; i++) {
    for (let j = 0; j < winPattern.length; j++) {
        for (let n = 0; n < winPattern[0].length; n++) {
            if (placePieces[i] === winPattern[j][n]) {
                //Prints out the matches and mismatches
                console.log(`It matches: Piece: ${placePieces[i]} //\\ Pattern: ${winPattern[j][n]}`);

                continue nextPiece;
            } else {
                console.log(`It doesn't match: Piece: ${placePieces[i]} //\\Pattern: ${winPattern[j][n]}`);
            }
        }
    }
}

我希望 placePieces 数组将值与 winPattern 2d 数组中的每个 SET 数组进行比较。

【问题讨论】:

  • 提示: 您可以使用数组函数在一行中检查,如下所示:let winCheck = winPattern.some(pat =&gt; pat.every(pos =&gt; placePieces.includes(pos))); 仅检查 winPatterns 中是否存在模式 pat其所有元素都包含在placePieces 中。减少头痛!

标签: javascript arrays for-loop multidimensional-array tic-tac-toe


【解决方案1】:

此代码应该可以查看用户当前数组是否与 answers 数组中的任何内容匹配 -

    var winPattern = [
        //horizontal
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],

        //vertical
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],

        //diagonal
        [0, 4, 8],
        [2, 4, 6]
  ];
//positions that o or x would be in tictactoe
var placePieces = [0, 1, 2, 4, 8, ];
var count = 0;

function arraysEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length != b.length) return false;


  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}


function checkMatch(arr){
  for(var i = 0; i < winPattern.length; i++){
    for(var j = 0; j < arr.length - 2; j++){
      for(var k = j + 1; k < arr.length - 1; k++){
        for(var l = k + 1; l < arr.length; l++){
          var possibleAnswer = [arr[j], arr[k], arr[l]];
          if(arraysEqual(possibleAnswer, winPattern[i])) return true;
        }
      }
    }
  }
  return false;
}

这是假设 placePieces 已排序,因为它似乎在您的示例中。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 2022-01-20
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2019-03-18
    • 2019-12-04
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多