我們可能最常使用打亂數(shù)組順序的方法是 Array.prototype.sort
:
const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5)
但這種方法不是完全隨機(jī)的哈肖。
我們可以使用 Fisher-Yates Shuffling 算法對(duì)數(shù)組進(jìn)行隨機(jī)排序。
原理:遍歷數(shù)組元素,然后將當(dāng)前元素與之后隨機(jī)位置的元素進(jìn)行交換。
function shuffle(arr) {
let currentIndex = arr.length, randomIndex
while (currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex--)
;[arr[randomIndex], arr[currentIndex]] = [arr[currentIndex], arr[randomIndex]]
}
return arr
}
const list = [1, 2, 3, 4, 5, 6, 7, 8]
shuffle(list)
JS 有很多工具庫(kù)使用到了這種算法神僵,例如 Lodash 和 Underscore 的 _.shuffle(collection)
方法熊经。