
Fair Random Selection: Why Shuffling a List Wrong Gives Biased Results
Pick a random item from a list. Sounds trivial. And for a single selection it is: generate a random index from 0 to length-1, return that item. But the moment you need to select multiple items, ensure fairness, or shuffle a list, the naive approach introduces bias. The Fisher-Yates shuffle The correct algorithm for shuffling a list is Fisher-Yates (also called Knuth shuffle). It works backward through the array, swapping each element with a randomly selected element from the remaining unshuffled portion: function shuffle ( array ) { for ( let i = array . length - 1 ; i > 0 ; i -- ) { const j = Math . floor ( Math . random () * ( i + 1 )); [ array [ i ], array [ j ]] = [ array [ j ], array [ i ]]; } return array ; } This produces every possible permutation with equal probability. The key is Math.random() * (i + 1) , which selects from 0 to i (inclusive). Using Math.random() * array.length instead (selecting from the entire array on every iteration) produces biased results. Proving the b
Continue reading on Dev.to Tutorial
Opens in a new tab



