使用sort()排序方法
function shuffled_1(n) {
const arr = Array.from(Array(n).keys());
arr.sort(() => Math.random() - 0.5);
return arr;
}
let s1 = shuffled_1(10);
console.log(s1);
使用 Fisher-Yates 洗牌算法
function shuffled_2(n) {
const arr = Array.from(Array(n).keys())
for(i = 0
let j = Math.floor(Math.random()*(i+1))
[arr[i], arr[j]] = [arr[j], arr[i]]
}
return arr
}
let s2 = shuffled_2(10)
console.log(s2)
用随机插入法进行打乱顺序
function shuffled_3(n) {
const arr = Array.from(Array(n).keys())
const shuffledArr = []
/**
* 1. 准备一个空数组
* 2. 从 arr 数据中随机取一个放入 shuffledArr 数组中
* 3. 直到数组 arr 为空。
*/
while(arr.length >0 ) {
const i = Math.floor(Math.random()*( arr.length ))
shuffledArr.push(arr.splice(i, 1)[0])
}
return shuffledArr
}
let s3 = shuffled_3(10)
console.log(s3)
为了看起来平衡
- 可以使用合适的算法,比如用Fisher-Yates洗牌算法。
- 对数组进行多次打乱,每次使用不同的打乱算法,增加打乱的随机性。