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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>

/*
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:
    - std::vector<std::string> for the deck
    - std::shuffle for efficient randomization
    - std::mt19937 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
*/

std::vector<std::string> buildDeck() {
    const std::vector<std::string> ranks = {
        "2","3","4","5","6","7","8","9","10","J","Q","K","A"
    };
    const std::vector<std::string> suits = {
        "Clubs", "Diamonds", "Hearts", "Spades"
    };

    std::vector<std::string> deck;
    deck.reserve(52);

    for (const auto& suit : suits) {
        for (const auto& rank : ranks) {
            deck.push_back(rank + " of " + suit);
        }
    }

    return deck;
}

void drawFive(std::vector<std::string>& deck, int drawNumber, std::mt19937& gen) {
    // Shuffle the remaining deck before this draw
    std::shuffle(deck.begin(), deck.end(), gen);

    std::cout << "Draw #" << drawNumber << ":\n";
    for (int i = 0; i < 5; ++i) {
        std::cout << "  " << deck[i] << "\n";
    }
    std::cout << "\n";

    // Remove the drawn cards from the deck
    deck.erase(deck.begin(), deck.begin() + 5);
}

int main() {
    // Number of draws
    int draws = 3;

    // Build the deck
    std::vector<std::string> deck = buildDeck();

    // Random engine
    std::random_device rd;
    std::mt19937 gen(rd());

    // Perform multiple draws (no duplicates, shuffle before each draw)
    for (int i = 1; i <= draws; ++i) {
        if (deck.size() < 5) {
            std::cout << "Not enough cards left for draw #" << i << ".\n";
            break;
        }
        drawFive(deck, i, gen);
    }
}


/*
run:

Draw #1:
  9 of Hearts
  5 of Diamonds
  10 of Clubs
  2 of Hearts
  9 of Clubs

Draw #2:
  4 of Clubs
  Q of Hearts
  A of Diamonds
  J of Clubs
  J of Diamonds

Draw #3:
  7 of Hearts
  7 of Clubs
  8 of Clubs
  2 of Clubs
  5 of Hearts

*/

 



answered 1 day ago by avibootz

Related questions

...