查找数组中的任何一个数组中是否存在很少的数组项目



有这两个JavaScript数组

// The player which has a "winning" combination (1, 5, 9)
player1Cells = [ 5, 9, 1, 6] 
// Player which doesnt have a "winning" combination
player2Cells = [ 2, 1, 4, 8]

如果其中3个数字与此数组中的一个数组相匹配,则玩家具有"获胜"组合:

winningCombinations = [
    [1, 2, 3], [4, 5, 6], [7, 8, 9],
    [1, 4, 7], [2, 5, 8], [3, 6, 9],
    [1, 5, 9], [3, 5, 7]
];

在示例中,player1Cells具有获胜组合-1,5,9。另一个玩家没有

我认为有一种方法可以以某种方式循环浏览winningCombinations,并将其与玩家进行比较,但我不知道以有效的方式比较它们的最佳方法。

您可以在获胜数组上使用some方法,然后filter方法检查播放器在某个循环中是否有3个以上的匹配项。

const w = [[1, 2, 3], [4, 5, 6], [7, 8, 9],[1, 4, 7], [2, 5, 8], [3, 6, 9],[1, 5, 9], [3, 5, 7]];
const player1Cells = [ 5, 9, 1, 6];
const player2Cells = [ 2, 1, 4, 8];
function check(arr, p) {
  return arr.some(a => {
    const match = p.filter(e => a.includes(e));
    return match.length >= 3;
  })
}
console.log(check(w, player1Cells));
console.log(check(w, player2Cells));

您可以使用:

  • Array.prototype.some()
  • Array.prototype.every()
  • Array.prototype.includes()

工作示例:

let player1Cells = [5, 9, 1, 6];
let player2Cells = [2, 1, 4, 8];
let winningCombinations = [
    [1, 2, 3], [4, 5, 6], [7, 8, 9],
    [1, 4, 7], [2, 5, 8], [3, 6, 9],
    [1, 5, 9], [3, 5, 7]
];
let checker = function(w, p) {
  return w.some(a => a.every(v => p.includes(v)));
}
console.log(checker(winningCombinations, player1Cells));
console.log(checker(winningCombinations, player2Cells));

相关内容

  • 没有找到相关文章

最新更新