How to pick 5 random cards from a 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 picks 5 random cards from a standard 52‑card deck.

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

    Algorithm:
    1. Build the deck (52 strings).
    2. Shuffle using Fisher–Yates.
    3. Print the first 5 cards.
*/

class Program
{
    // Build a full 52‑card deck
    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);

        // Combine each rank with each suit → 52 unique cards
        foreach (string suit in suits) {
            foreach (string rank in ranks) {
                deck.Add($"{rank} of {suit}");
            }
        }

        return deck;
    }

    // Shuffle the deck using Fisher–Yates
    static void ShuffleDeck(List<string> deck)
    {
        Random rng = new Random();

        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 Main()
    {
        // Step 1: Build the deck
        List<string> deck = BuildDeck();

        // Step 2: Shuffle the deck
        ShuffleDeck(deck);

        // Step 3: Draw the first 5 cards
        Console.WriteLine("Your 5 random cards:");
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine(deck[i]);
        }
    }
}


/*
run:

Your 5 random cards:
9 of Spades
J of Diamonds
A of Spades
5 of Diamonds
2 of Hearts

*/

 



answered 1 day ago by avibootz
...