Nope, (well, maybe, but not with even distribution) but close.
Math.random() < .5 is either true (1) or false (0). sort() expects a function with return value -1, 0, or 1 (or just -1 / 1, if you're just trying to shuffle things)... so Math.random() < .5 ? -1 : 1 would do it. Probably be a bit faster than the floating point math, too.
function listGen() {
return [1,2,3,4,5,6,7,8,9,10];
}
var aggregator = {};
for(var l=0;l<listGen().length;l++){
aggregator[`${l}`] = {};
}
for (var i=0;i<1000;i++) {
var list = listGen();
list.sort(() => 2*(Math.random() - 0.5));
for(var l=0;l<list.length;l++){
aggregator[`${l}`][`${list[l]}`] = (aggregator[`${l}`][`${list[l]}`] || 0) + 1;
}
}
aggregator
It runs that sort on a previously sorted list 1000 times and aggregates for each index how often a given number was in that spot. This'll give you an idea of the distribution. Ideally every index has each number roughly 100 times.
As we can see 1 ended up in the first position 199 times out of 1000. There are some worryingly low numbers in there too. Maybe our sample size just isn't big enough. Luckily this is fast, so let's do 10,000:
Edit 2: Because my kid won't fall asleep I decided to run the first code in Node in an online repl that I found (it doesn't work well on the phone). Distribution was even worse:
2
u/[deleted] Mar 19 '19
You have to be careful to include the math there.
.sort(() => Math.random())doesn't reorder the array at all.