虚假的洗牌算法

虚假的洗牌算法

最常见的:

const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5)

可这并不合理,对于这个数组:[1,2,3,4,5],每个数字出现在每个位置的概率应该是相同的。然而使用以上算法,1 出现在 index=4 位置的概率 与 4 出现在 index=4 的概率并不相同。

真正的洗牌算法

Fisher–Yates shuffle

const nums = Array(54)
.fill(undefined)
.map((_, index) => index)

/**
* 洗牌算法
* @param nums 数组
*/
function FYSufffle(nums) {
const randNums = Array.from(nums)
let len = nums.length
while (len > 1) {
const rand = Math.floor(Math.random() * len)
len--
// 交换
;[randNums[rand], randNums[len]] = [randNums[len], randNums[rand]]
}
return randNums
}

console.log(FYSufffle(nums))

以上。