洗牌算法

Source Code

Array.prototype.shuffle = function shuffler() {
  for (let i = 0; i < this.length - 1; i++) {
    let pick = Math.floor(Math.random() * (this.length - i));
    if (pick !== 0) {
      let item = this[pick + i];
      this[pick + i] = this[i];
      this[i] = item;
    }
  }
  return this;
};

Usage

let a = Array(10)
  .fill(0)
  .map((_, i) => i);
// a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a.shuffle()
// a = [6, 7, 9, 0, 2, 1, 5, 4, 8, 3]

你可能感兴趣的:(洗牌算法)