Skip to main content

Command Palette

Search for a command to run...

Shuffling an Array in C#

Updated
2 min read
Shuffling an Array in C#

I was using Arrays as part of making a Blackjack game, which was a college assessment. I used multiple Arrays to create a deck of cards, see my other post "Creating a deck of cards in C#". But, now I needed to shuffle these cards, similar to how you would a normal deck of cards. I needed to find a way to mix this Array of cards up for the game to be more realistic.

Shuffling the deck

To shuffle the cards in the deck I knew I would need to use a Random method to select the cards to shuffle, but after that, I drew a blank. Similar to when I researched about creating a deck, it showed the same results linked to enum and list. From the research, I learned that I would need to set up a temporary card, and then move the random card chosen between the temporary card and another card.

How I shuffled my deck of cards…

In my code below, I created a card variable and set this to the first card in the deck. After this, I set up a for loop to run 720 (this can be anything, but should be a large number), within this loop I created a random card to choose within the length of the cards Array except for the first card in the Array, because this is the card we will change it to. As you can see, after the shuffle is set, the first card in the Cards Array has been set to the random card, the random card is then set to the variable(which has already been set at the beginning, to the Cards object at index[0]). This code then runs over the loop 720 times constantly swapping the first card to a random card in the deck.

public void ShuffleDeck()
{
    for (int shuffleNum = 0; shuffleNum < 720; shuffleNum++)
    {
        // pick the first card
        ...

        // pick a card that's not the first card
        int shuffleCardIndex = randomCard.Next(1, Cards.Length);

        // swap the first card with the shuffle card
        Cards[0] = Cards[shuffleCardIndex];
        Cards[shuffleCardIndex] = firstCard;
    }
}

This method is then called in the CreateDeck method on the Deck object, so when a deck is created it is automatically shuffled.

private Card[] CreateDeck()
 {
    ...

    ShuffleDeck();

    return Cards;
  }

Reference: Defining your cards and deck