我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
d3.js提供了Fisher–Yates shuffle的内置版本:
console.log(d3.shuffle([“a”,“b”,“c”,“d”]);<script src=“http://d3js.org/d3.v5.min.js“></script>
d3.洗牌(array[,lo[,hi]])<>使用Fisher–Yates混洗随机化指定阵列的顺序。
其他回答
只是为了在馅饼里插一根手指。在这里,我介绍了Fisher Yates shuffle的递归实现(我认为)。它给出了统一的随机性。
注意:~~(双颚化符运算符)实际上与正实数的Math.floor()类似。这只是一条捷径。
var shuffle=a=>a.length?a.splice(~~(Math.random()*a.length),1).contat(shuffle(a)):a;console.log(JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9]));
编辑:由于使用了.splice(),上面的代码是O(n^2),但我们可以通过交换技巧消除O(n)中的拼接和混洗。
var shuffle=(a,l=a.length,r=~~(Math.random()*l))=>l?([a[r],a[l-1]]=[a[l-1],a[r]],shuffle(a,l-1)):a;var arr=Array.from({length:3000},(_,i)=>i);console.time(“shuffle”);洗牌(arr);console.timeEnd(“shuffle”);
问题是,JS无法与大型递归合作。在这种特殊的情况下,数组大小会受到限制,大约为3000~7000,这取决于浏览器引擎和一些未知的事实。
使用Ramda的功能解决方案。
const {map, compose, sortBy, prop} = require('ramda')
const shuffle = compose(
map(prop('v')),
sortBy(prop('i')),
map(v => ({v, i: Math.random()}))
)
shuffle([1,2,3,4,5,6,7])
// Create a places array which holds the index for each item in the
// passed in array.
//
// Then return a new array by randomly selecting items from the
// passed in array by referencing the places array item. Removing that
// places item each time though.
function shuffle(array) {
let places = array.map((item, index) => index);
return array.map((item, index, array) => {
const random_index = Math.floor(Math.random() * places.length);
const places_value = places[random_index];
places.splice(random_index, 1);
return array[places_value];
})
}
添加到@Laurens Holsts的答案。这是50%的压缩。
function shuffleArray(d) {
for (var c = d.length - 1; c > 0; c--) {
var b = Math.floor(Math.random() * (c + 1));
var a = d[c];
d[c] = d[b];
d[b] = a;
}
return d
};
社区表示arr.sort((a,b)=>0.5-Math.random())不是100%随机的!对我测试并建议不要使用此方法!
let arr = [1, 2, 3, 4, 5, 6]
arr.sort((a, b) => 0.5 - Math.random());
但我不确定。所以我写了一些代码来测试!。。。你也可以试试!如果你足够感兴趣!
让data_base=[];对于(设i=1;i<=100;i++){//将100次新的rendom arr推送到data_base!数据基础推送([1,2,3,4,5,6]排序((a,b)=>{return Math.random()-0.5;//使用了社区禁止的方法!:-)}));}//console.log(data_base);//如果你想看数据!让分析={};for(设i=1;i<=6;i++){analysis[i]=阵列(6).填充(0);}for(假设num=0;num<6;num++){for(设i=1;i<=100;i++){let plus=数据基[i-1][num];分析[`${num+1}`][plus-1]++;}}console.log(分析);//分析结果
在100个不同的随机阵列中。(我的分析结果)
{ player> 1 2 3 4 5 6
'1': [ 36, 12, 17, 16, 9, 10 ],
'2': [ 15, 36, 12, 18, 7, 12 ],
'3': [ 11, 8, 22, 19, 17, 23 ],
'4': [ 9, 14, 19, 18, 22, 18 ],
'5': [ 12, 19, 15, 18, 23, 13 ],
'6': [ 17, 11, 15, 11, 22, 24 ]
}
// player 1 got > 1(36 times),2(15 times),...,6(17 times)
// ...
// ...
// player 6 got > 1(10 times),2(12 times),...,6(24 times)
正如你所看到的,这不是那么随机!苏。。。不要使用此方法!如果你测试多次,你会看到玩家1获得了很多次(1号)!而球员6在大多数时候都获得了(第6名)!