C#
Great job, everyone. Here's my own answer in C# based on the Fisher-Yates algorithm:
- Partially sort the deck until
deck[0] == 0
. Since you know that card's original value, you can use it as a counter and overwrite it as much as you like. - For each position
i
from 1 to 51, swap the card ati
with the one atrand(i, 51)
(note: NOTrand(1, 51)
. That won't give you a random shuffle). - Set
deck[0]
back to zero and swap it with a random card.
Should be a perfectly random shuffle.
public static void shuffle(int[] deck)
{
while (deck[0] > 0)
swap(ref deck[0], ref deck[deck[0]]);
for (deck[0] = 1; deck[0] < 52; deck[0]++)
swap(ref deck[deck[0]], ref deck[rand(deck[0], 51)]);
deck[0] = 0;
swap(ref deck[0], ref deck[rand(0, 51)]);
}
Javascript version:
while (deck[0] > 0)
swap(0, deck[0]);
for (deck[0] = 1; deck[0] < 52; deck[0]++)
swap(deck[0], rand(deck[0], 52));
deck[0] = 0;
swap(0, rand(0, 52));
...where swap(a, b)
swaps deck[a]
with deck[b]
.