Applied & Puzzles
Fisher–Yates shuffle
Algorithm · Stretch
Level: Stretch
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence—in plain terms, the algorithm shuffles the sequence. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain. The algorithm produces an unbiased permutation: every permutation is equally likely. The modern version of the algorithm is efficient: it takes time proportional to the number of items being shuffled and shuffles them in place.
Code
/**
* @param {*[]} originalArray
* @return {*[]}
*/
export default function fisherYates(originalArray) {
// Clone array from preventing original array from modification (for testing purpose).
const array = originalArray.slice(0);
for (let i = (array.length - 1); i > 0; i -= 1) {
const randomIndex = Math.floor(Math.random() * (i + 1));
[array[i], array[randomIndex]] = [array[randomIndex], array[i]];
}
return array;
}References
Spotted a mistake or something unclear? Report it on GitHub.