0

配列の配列で、特定の配列の要素を含む配列のインスタンスを検索する最良の方法を探しています。

今、私はそれが紛らわしい線であることを理解しています. そのため、シナリオを説明するための例を次に示します。

私は、9 つ​​のセルのゲーム ボードを表す 9 つの項目を持つ配列である検索セットを持っています。値は10またはnull:

var board = [1, 0, 1, 1, 0, 1, 0, 0, null];

配列の配列である結果セットもあります。

var winningCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

の各配列は配列内のインデックスwinningCombo表しており、これが勝利の組み合わせです。board

8つの勝利の組み合わせがあります。

各勝利の組み合わせは、値がすべて 1 の場合に勝利する 3 つのインデックスのグループです。

つまり、勝つために、ボードは次のようになります。

board = [1,1,1,0,0,0,null,null,0]; // Index 0,1, and 2 are 1, matching winningCombos[0]

また

board = [null,null,1,0,1,0,1,null,0]; // Index 2,4, and 6 are 1, matching winningCombos[7]

私の質問は:

Javascriptでこの操作を実行する方法は何ですか(おそらくES6で)?

私がこれまでに思いついたのはこれです:

const win = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
let board = [null,null,1,0,1,0,1,null,0];

let score = [];

board.forEach(function(cell, index) 
    {
      if(cell === 1) 
        score.push(index);
});
console.log(score);
console.log(win.indexOf(score) > -1)

しかし、配列の配列で配列を見つけるのに苦労していますscoreis[2,4,6]と thisの正確な配列は に存在しwinますが、Javascript でオブジェクトの等価性が機能する方法のため、結果には表示されません。

一言で言えば、私はscore存在するかどうかを確認しようとしていますwin

私はこの解決策を見つけましたが、かなりハッキーなようです。これを処理するより良い方法はありますか?

4

2 に答える 2

4

を使用Array.prototype.some()して、Array.prototype.every()の各要素を確認できますwinscore

const win = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
];
let board = [null, null, 1, 0, 1, 0, 1, null, 0];

let score = [];

board.forEach(function(cell, index) {
  if (cell === 1)
    score.push(index);
});
console.log(score);
let bool = win.some(function(arr) {
  return arr.every(function(prop, index) {
    return score[index] === prop
  })
});
console.log(bool);

于 2016-11-11T18:11:36.480 に答える
1

ES6 を使用するwinと、これらの場所のそれぞれで配列を実際の値にマップできます。

const win = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
let board = [null,null,1,0,1,0,1,null,0];
let winning_spots = win.map((spots) => spots.map((i) => board[i]));
>>> winning_spots
[[null, null, 1], [0, 1, 0], [1, null, 0], [null, 0, 1], [null, 1, null], [1, 0, 0], [null, 1, 0], [1, 1, 1]]

次に、どれがすべて 1 または 0 であるかによってフィルタリングできます。

let one_winners = winning_spots.filter((spots) => spots.every((e) => e == 1));
let zero_winners = winning_spots.filter((spots) => spots.every((e) => e == 0));
>>> one_winners
[[1, 1, 1]]
>>> zero_winners
[]

最後に、勝者がいるかどうかを知りたい場合は、長さを確認してください。

let is_winner = (one_winners.length + zero_winners.length) > 0
于 2016-11-11T18:09:43.597 に答える