Skip to main content
4 of 5
added 272 characters in body

C#

Great job, everyone. Here's my own answer in C# based on the Fisher-Yates algorithm:

  1. 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.
  2. For each position i from 1 to 51, swap the card at i with the one at rand(i, 51) (note: NOT rand(1, 51). That won't give you a random shuffle).
  3. 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].