DEV Community

Discussion on: Some Powerful Js One-liners

Collapse
 
m90 profile image
Frederik Ring

Nice post. Be aware that shuffling an Array like this is not perfectly random and a proper implementation is a little more complicated: medium.com/@nitinpatel_20236/how-t...

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Very interesting, I hadn't considered how using sort like that could end up with an infinite loop!

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited

In case anyone is interested, I plotted the distributions for the Math.random() - 0.5 and the Fisher-Yates shuffles.

Chart of shuffle using Math.random() - 0.5. Shows clearly uneven distribution

Chart of Fisher-Yates shuffle algorithm. Shows a distribution much closer to even

That's 100000 shuffles of abcd for each algorithm.