JavaScript随机打乱数组元素的算法
Fisher–Yates算法
随机打乱数组元素有一种算法:Fisher–Yates,JavaScript实现如下:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// 循环打乱剩下的元素
while (0 !== currentIndex) {
// 抽取剩下的元素
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// 和当前元素交换
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
使用:
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
Durstenfeld shuffle算法
Fisher-Yates优化版Durstenfeld shuffle, JavaScript实现如下:
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
ES6b版本:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}