How to perform multiple 5‑card draws from a shuffled 52‑card deck in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

/*
A standard deck of 52 playing cards consists of four suits:
spades (♠), hearts (♥), diamonds (♦), and clubs (♣).

Each suit contains 13 ranks:
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.

Cards of spades and clubs are black, while hearts and diamonds are red.

Color is informational only — it does not affect shuffling or random selection.
*/

/*
    This program performs multiple draws of 5 random cards from a 52‑card deck
    WITHOUT duplicates across draws.

    It uses:
    - List<string> for the deck
    - Fisher–Yates shuffle for efficient randomization
    - Random for high‑quality randomness

    Algorithm:
    1. Build a full deck (52 cards)
    2. For each draw:
       a. Shuffle the remaining deck
       b. Draw 5 cards
       c. Remove them from the deck
*/

class Program
{
    static List<string> BuildDeck()
    {
        string[] ranks = { "2","3","4","5","6","7","8","9","10","J","Q","K","A" };
        string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };

        List<string> deck = new List<string>(52);

        foreach (string suit in suits) {
            foreach (string rank in ranks) {
                deck.Add($"{rank} of {suit}");
            }
        }

        return deck;
    }

    static void ShuffleDeck(List<string> deck, Random rng)
    {
        // Fisher–Yates shuffle
        for (int i = deck.Count - 1; i > 0; i--) {
            int j = rng.Next(i + 1);
            string temp = deck[i];
            deck[i] = deck[j];
            deck[j] = temp;
        }
    }

    static void DrawFive(List<string> deck, int drawNumber, Random rng)
    {
        // Shuffle the remaining deck before this draw
        ShuffleDeck(deck, rng);

        Console.WriteLine($"Draw #{drawNumber}:");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("  " + deck[i]);
        }
        Console.WriteLine();

        // Remove drawn cards
        deck.RemoveRange(0, 5);
    }

    static void Main()
    {
        // Number of draws
        int draws = 3;

        List<string> deck = BuildDeck();
        Random rng = new Random();

        // Perform multiple draws (no duplicates)
        for (int i = 1; i <= draws; i++) {
            if (deck.Count < 5) {
                Console.WriteLine($"Not enough cards left for draw #{i}.");
                break;
            }

            DrawFive(deck, i, rng);
        }
    }
}


/*
run:

Draw #1:
  10 of Clubs
  8 of Hearts
  6 of Diamonds
  10 of Diamonds
  K of Diamonds

Draw #2:
  9 of Hearts
  K of Spades
  5 of Diamonds
  5 of Clubs
  K of Clubs

Draw #3:
  J of Hearts
  A of Clubs
  7 of Diamonds
  3 of Hearts
  J of Clubs

*/

 



answered 10 hours ago by avibootz

Related questions

...