保留原值
长度任意,保留原值,返回新数组。
1 2 3 4 5 6 7
| shuf = (arr) => Array.prototype.reduce.call(arr,(acc, el) => { acc.push(el) let i = Math.floor(Math.random() * (acc.length)) ;[acc[i], acc[acc.length - 1]] = [acc[acc.length - 1], acc[i]] return acc },[])
|
要不顺便写个运气测试……?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function looksRandom(shuf) { let rat = [0, 1, 2, 3, 4] let perms = permutation(rat) let attempts = perms.length * 2333 let luck = {} for (let i = 0; i < attempts; i++) luck[shuf(rat).join(',')] = (luck[shuf(rat).join(',')] >>> 0) + 1 for (j of perms) if (typeof luck[j.join(',')] === 'undefined') { console.log(j) return false } console.log(luck) return "maybe" }
looksRandom(shuf) looksRandom((arr) => (arr.sort(() => Math.random() - 0.5), arr))
|
Author:蓝思同学
Permalink:https://www.lancema.com/posts/2021/study/javascript实现数组随机排序.html
Slogan:small is beautiful, small is powerful !