Zyzle.dev

Fisher-Yates Shuffle

18th February, 2023

The Fisher-Yates shuffle, example in Typescript

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;
}
}

The pseudo-code for this algorithm is as follows:

for i from n-1 downto 1 do
j <- random integer such that 0 <= j <= i
exchange a[j] and a[i]