两个思路
- 随机交换
function shuffle(arr) { arr.forEach((_, idx) => { const targetIdx = Math.floor(Math.random() * arr.length) ;[arr[idx], arr[targetIdx]] = [arr[targetIdx], arr[idx]] }) return arr}shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])// => [6, 4, 1, 8, 5, 2, 10, 9, 3, 7] or else
- 打乱下标(慢了 300-1000 倍左右)
function shuffleSubscript(n) { const arr = new Array(n) for (let i = 0; i < n; i++) { let val do val = Math.floor(Math.random() * n) while (arr.includes(val)) arr[i] = val } return arr}function shuffle(arr) { return shuffleSubscript(arr.length).map(s => arr[s])}shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])// => [7, 4, 5, 8, 6, 3, 1, 2, 10, 9] or else
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)