This does not make a uniform distribution for all (any?) sizes of arrays. I ran into an issue with one version of v8 where this consistently made an array of 1-10 reversed. I'm on my phone but if I remember tomorrow I should write something up about this
Right-- even if Math.random is random, you still have to subtract 0.5 from it to get a number from -0.5 to +0.5, because sort uses negative-number/positive-number to determine how to order two values.
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/barrtender Mar 19 '19 edited Mar 19 '19
This does not make a uniform distribution for all (any?) sizes of arrays. I ran into an issue with one version of v8 where this consistently made an array of 1-10 reversed. I'm on my phone but if I remember tomorrow I should write something up about this
Edit - I put some more info below about the distribution. https://www.reddit.com/r/javascript/comments/b2o6f2/whats_your_favorite_most_useful_javascript/eiwrgp9/