随机洗牌

Tags
algorithm
Created
May 22, 2016 4:31 PM

使用数组的 sort 进行洗牌不正确,取决于排序算法

应该使用 random 随机数交换元素

Array.prototype.shuffle = function(){
  for (var i = this.length - 1; i >= 0; i--) {
    var r = Math.floor(Math.random()*(i+1));
    temp = this[i];
    this[i] = this[r];
    this[r] = temp;
  }
  return this;
}
SuperMade with Super