数组洗牌 Fisher Yates
看播放器代码时发现的这个洗牌算法,再网上查了一番
作用是把数组变成随机序列,原理类似于从牌堆A中随机抽牌放进牌堆B
代码1: 返回一个由(数组下标)组成的数组
function random(length) {
function shuffle (arr) {
for (let i = arr.length - 1; i >= 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1));
const itemAtIndex = arr[randomIndex];
arr[randomIndex] = arr[i];
arr[i] = itemAtIndex;
}
return arr;
}
return shuffle([...Array(length)].map(function (item, i) {
return i;
}));
}
代码2:
function shuffle(array) {
var copy = [],
n = array.length,
i;
// 如果还剩有元素则继续。。。
while (n) {
// 随机抽取一个元素
i = Math.floor(Math.random() * array.length);
// 如果这个元素之前没有被选中过。。
if (i in array) {
copy.push(array[i]);
delete array[i];
n--;
}
}
return copy;
}
浙公网安备 33010602011771号