web-dev-qa-db-ja.com

JavaScript配列をシャッフルするにはどうすればよいですか?

Angular6プロジェクトで配列の順序をランダム化しようとしています。方法がわからず、Math.random()関数を使用して配列を並べ替えようとしました...(XDは機能しませんでした)

これはこれまでの私のコードです:

[〜#〜] html [〜#〜]

    <div style="background: darkcyan; width: 600px; height: 600px; margin: auto">
  <table>
    <tr *ngFor="let card of cards">
      <div id="{{card.id}}" [ngStyle]="{'background-color': card.color}" style=" width: 100px; height: 125px; margin: 5px"></div>
    </tr>
  </table>
</div>
<button (click)="shuffle()">Shuffle Cards</button>

TypeScript

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-memory-game',
  templateUrl: './memory-game.component.html',
  styleUrls: ['./memory-game.component.css']
})
export class MemoryGameComponent implements OnInit {
  cards = [];
  constructor() { }

  ngOnInit() {
    this.cards = [
        {
          'id': 1,
          'color': 'red'
        },
        {
            'id': 2,
            'color': 'green'
        },
        {
            'id': 3,
            'color': 'blue'
        },
        {
            'id': 4,
            'color': 'yellow'
        }
    ];
      this.shuffle();
  }

  public shuffle() {
      this.cards.sort(Math.random);
  }
}

簡単な解決策があるかどうかはわかりませんが、誰かが私を助けてくれることを本当に望んでいます。

ありがとう

3
Marcus Scharf

このシャッフル機能を試してください。

_function shuffle(arrParam: any[]): any[]{
    let arr = arrParam.slice(),
        length = arr.length,
        temp,
        i;

    while(length){
        i = Math.floor(Math.random() * length--);

        temp = arr[length];
        arr[length] = arr[i];
        arr[i] = temp;
    }

    return arr;
}
_

これは純粋関数であり、任意の配列で使用できます。元の配列を保持した新しいシャッフル配列を作成します。

テンプレートで機能させて_this.cards_をソートする場合は、_this.cards_を変更するコンポーネントメソッドshuffle()を作成できます。

_public shuffle(): any[]{
    let arr = this.cards.slice(),
        length = arr.length,
        temp,
        i;

    while(length){
        i = Math.floor(Math.random() * length--);

        temp = arr[length];
        arr[length] = arr[i];
        arr[i] = temp;
    }

    this.cards = arr;
}
_

編集:彼がコメントで提供した@wannadreamリンクを確認したところ、上記のshuffle関数は「事実上の不偏シャッフルアルゴリズムはフィッシャー-イェーツ(別名クヌース)シャッフル」のようです。フィッシャー-イェーツシャッフルアルゴリズムを参考にして書いたに違いありません。

0
codeepic