-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
- 实现一个函数,传入的参数是一个数组,返回一个新数组使得原数组中每个元素等概率的出现在各个下标上。
function shuffle(arr) {
return arr.sort(function(a, b) {
return Math.random() > 0.5 ? (a - b) : (b - a);
});
}
console.log(shuffle([1, 2, 3]))
方法二:利用随机数生成器
function shuffle(arr) {
const MAX_VALUE = Math.pow(2, 1000);
console.log(arr);
// 为什么不能用item=>{value:item}的简写形式?
let weight = arr.map(item=>{
return {value: item};
});
console.log(weight);
// 在一个范围内生成一个随机数作为数组中每个元素的权重
for(let i = 0; i < arr.length; i++) {
let w = getRandomInt(MAX_VALUE);
weight[i].weight = w;
}
// 按照数组中每个元素的权重来进行排序
weight.sort((a, b)=>a.weight - b.weight);
return weight.map(item=>item.value);
}
function getRandomInt(max) {
return Math.floor(Math.random()*Math.floor(max));
}
let test = [123, 5241, 7, 1987, 6524];
console.log(shuffle(test));
Metadata
Metadata
Assignees
Labels
No labels