xiaoxiaosaohuo/Note

费耶·伊茨洗牌算法

Opened this issue · 0 comments

如果你想和朋友一起玩德州扑克游戏,你应该首先洗牌,随机选择秩序并保证公平的比赛。

一个简单而有效的方式是从牌堆里反复取出一张随机牌,并将其放在一边,逐步建立一个新的堆栈,只要以相等的概率从牌堆上挑选每张剩余的牌,完成之后就会有一个完美无缺的随机堆栈.

但是怎么用代码实现?

第一种

function shuffle(array) {
  var copy = [], n = array.length, i;

  // While there remain elements to shuffle…
  while (n) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * array.length);

    // If not already shuffled, move it to the new array.
    if (i in array) {
      copy.push(array[i]);
      delete array[i];
      n--;
    }
  }

  return copy;
}

第二种

function shuffle(array) {
  var copy = [], n = array.length, i;

  // While there remain elements to shuffle…
  while (n) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * n--);

    // And move it to the new array.
    copy.push(array.splice(i, 1)[0]);
  }

  return copy;
}

第三种

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

最后一种写法,效率最好,直接在原数组中操作,后部分存储已经洗牌的,前部分存未洗牌的。