If the function returns > 0, the first param should be sorted to a higher index than the second.
If the function returns < 0, the first param should be sorted to a lower index than the second.
If the function returns exactly zero, the parameters are left as they are.
So what we've got is a 1/3 of Erin 'winning', 1/3 of Thomas 'winning' and a 1/3 chance of a tie which leaves Erin ahead. So she's got a 2/3 chance of being first.
Additionally (but not in any consequential fashion), generating a random number between 1 and 100 (inclusive) gives you 100 possibilities (duh). With three outcomes:
100 / 3 = 33.333333333333336
The first option has slightly more chance to be picked. If Erin wanted to be fair(er), she'd multiply by 99.Here's a Python solution showing it's not just JS:
link: http://paste.ubuntu.com/23222240/
results:
{
'Erin Ptacek': 6523,
'Thomas Ptacek': 1951,
'Jeremy Rauch': 1526
}
(with apologies to
ShaneWilton, I've completely rewritten this comment so the following comments are out of date)It just so happens that in V8, the built-in sort uses an unstable quicksort for large arrays but a stable insertion sort for small ones, so the rest of your analysis is correct.
Even after changing the code to multiply by 99 instead of 100, the results don't change very much at all.
{ '0': 340364, '1': 330093, '-1': 329543 }
So we see a slight bias for zero (elements are equal) there. ~Lemme try it in Chrome and get back to you.~AHA, repro'd in Chrome latest: http://jsbin.com/cefuqi/edit?js,console
Also repros in node. Fascinating. There goes my afternoon...
Instead giving each name a distinct value (between 0 and 1) and sort based on those values.
MS took advantage of this when selecting a random browser for the browser ballot years ago.
http://www.robweir.com/blog/2010/02/microsoft-random-browser...
> compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
It doesn't really matter what Math.random() is producing when the sort algorithm is undefined.
Good luck with the company, I hope you can also beat the RNG that makes or breaks a startup :)