How to pick 5 random cards from a 52‑card deck in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*
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:
    - Arrays of strings to represent ranks and suits
    - A 52‑element array to store the deck
    - Fisher–Yates shuffle (the efficient, unbiased shuffle algorithm)
    - rand() seeded with time(NULL) for randomness

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

void buildDeck(char deck[][20]) {
    const char *ranks[] = {
        "2","3","4","5","6","7","8","9","10","J","Q","K","A"
    };

    const char *suits[] = {
        "Clubs", "Diamonds", "Hearts", "Spades"
    };

    int index = 0;

    // Build the deck: 13 ranks × 4 suits = 52 cards
    for (int s = 0; s < 4; s++) {
        for (int r = 0; r < 13; r++) {
            snprintf(deck[index], 20, "%s of %s", ranks[r], suits[s]);
            index++;
        }
    }
}

void shuffleDeck(char deck[][20], int size) {
    // Fisher–Yates shuffle: efficient and unbiased
    for (int i = size - 1; i > 0; i--) {
        int j = rand() % (i + 1);

        char temp[20];
        snprintf(temp, 20, "%s", deck[i]);
        snprintf(deck[i], 20, "%s", deck[j]);
        snprintf(deck[j], 20, "%s", temp);
    }
}

int main() {
    char deck[52][20];

    // Step 1: Build the deck
    buildDeck(deck);

    // Step 2: Seed RNG with current time
    srand((unsigned)time(NULL));

    // Step 3: Shuffle the deck
    shuffleDeck(deck, 52);

    // Step 4: Draw the first 5 cards
    printf("Your 5 random cards:\n");
    for (int i = 0; i < 5; i++) {
        printf("%s\n", deck[i]);
    }

    return 0;
}


/*
run:

Your 5 random cards:
6 of Diamonds
5 of Clubs
Q of Clubs
6 of Hearts
J of Clubs

*/

 



answered 1 day ago by avibootz
...