參考
如何測試洗牌程序
Fisher–Yates shuffle 洗牌算法
隨機洗牌算法
洗牌算法shuffle
如何為德撲圈設計洗牌算法
迭代步驟演示
1.倒序循環這個數組
2.取范圍從1到n的隨機數k
3.k與n交換
4.直到循環至數組的首個元素
/**
* Fisher–Yates shuffle
*/
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
使用方式也很簡單,直接用數組調用這個方法即可
[1,2,3,4,5,6,7,8].shuffle()
//[4, 6, 3, 2, 5, 1, 7, 8] // 每次結果都是隨機的