You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let arr= [1,2,3,4,5,6,7,8,9,10];
arr.map((item,index)=>{
let random =Math.floor(Math.random() * arr.length);
[arr[index],arr[random]] = [arr[random],arr[index]];
});
console.log(arr);
Activity
AnsonZnl commentedon May 10, 2019
直接使用原生的
sort()
方法:Mojitooooooooo commentedon May 10, 2019
使用array.sort()进行乱序存在一定问题,增大样本进行实验之后可以发现这种乱序方案并不是完全随机的(所有元素会大概率停留在自己的初始位置)(v8处理排序是小于10个是插入排序,大于10个是快排,排序算法复杂度介于O(n)与O(n2)之间,也就是存在两个元素都没有比较的机会,因此不是完全随机),这里可以使用Fisher–Yates shuffle(洗牌算法)
Array.prototype.shuffle = function() { var input = this; for (var i = input.length-1; i >=0; i--) { var randomIndex = Math.floor(Math.random()*(i+1)); var itemAtIndex = input[randomIndex]; input[randomIndex] = input[i]; input[i] = itemAtIndex; } return input; } var tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] tempArray.shuffle(); console.log(tempArray);
tiezhu92 commentedon May 10, 2019
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const map = new Map();
arr = arr.map(v => {
const random = Math.random();
map.set(random, v);
return random
}) //arr 替换成随机数, 原数组成员存入map
.sort((a, b) => a - b) //排序随机数
.map(v => map.get(v)); //取出数组成员填入数组
console.log(arr);
naokimidori commentedon May 10, 2019
arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});
[-][js] 第25天 如何快速让一个数组乱序,写出来[/-][+][js] 第24天 如何快速让一个数组乱序,写出来[/+]qqdnnd commentedon May 17, 2019
tzjoke commentedon May 28, 2019
为什么楼上要用三元运算符,直接这样不就完事了。。
不过我们team随机算法也用的洗牌算法,思路就是从后往前遍历,然后随机(0, i+1),交换
myprelude commentedon Jun 13, 2019
shufangyi commentedon Jul 22, 2019
klren0312 commentedon Jul 23, 2019
前面有些, 为啥发之前不先测试下...
加个判断吧.
Vi-jay commentedon Jul 29, 2019
seho-dev commentedon Aug 11, 2019
//洗牌数组
export function shuffle(arr) {
const _arr = arr.slice();
for (let i = 0; i < _arr.length; i++) {
//调用
let j = getRandomNumber(0, i);
let t = _arr[i];
_arr[i] = _arr[j];
_arr[j] = t;
}
return _arr;
}
//随机取0-1中间值(包括0和1)
export function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1));
}
zivenday commentedon Aug 26, 2019
大神,想问下,arr.sort(function(a,b){return Math.random() > 0.5 ? 1 : -1}),这种呢随机不是和Math.random的值密切相关吗,和sort有关系么?我的理解是sort是按照Math.random来排序,Math.random是完全随机的吧,那么这个整体应该也是完全随机的吧
23 remaining items