Fisher-Yates Shuffle
18th February, 2023
The Fisher-Yates shuffle1 is an algorithm for generating a random permutation of an array.
The algorithm is defined as follows:
-- To shuffle an array a of n elements (indices 0..n-1):for i from n-1 down to 1 do j ← random integer such that 0 ≤ j ≤ i exchange a[j] and a[i]
The typescript implementation of the algorithm I normally use is:
shuffle(cards: any[]) { let m = cards.length; let t, i = 0; while(m) { i = Math.floor(Math.random() * m--); t = cards[m]; cards[m] = cards[i]; cards[i] = t; }}