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

1 Answer

0 votes
program RandomCards;

{
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 (efficient and unbiased)
    - Randomize + Random for randomness

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

uses
    SysUtils;

type
    TDeck = array[0..51] of string;

procedure BuildDeck(var deck: TDeck);
const
    ranks: array[0..12] of string =
        ('2','3','4','5','6','7','8','9','10','J','Q','K','A');
    suits: array[0..3] of string =
        ('Clubs', 'Diamonds', 'Hearts', 'Spades');
var
    s, r, index: Integer;
begin
    index := 0;

    { Build the deck: 13 ranks × 4 suits = 52 cards }
    for s := 0 to 3 do
        for r := 0 to 12 do
        begin
            deck[index] := ranks[r] + ' of ' + suits[s];
            Inc(index);
        end;
end;

procedure ShuffleDeck(var deck: TDeck);
var
    i, j: Integer;
    temp: string;
begin
    { Fisher–Yates shuffle: efficient and unbiased }
    for i := 51 downto 1 do
    begin
        j := Random(i + 1);

        temp := deck[i];
        deck[i] := deck[j];
        deck[j] := temp;
    end;
end;

var
    deck: TDeck;
    i: Integer;

begin
    { Step 1: Build the deck }
    BuildDeck(deck);

    { Step 2: Seed the random number generator }
    Randomize;

    { Step 3: Shuffle the deck }
    ShuffleDeck(deck);

    { Step 4: Draw the first 5 cards }
    Writeln('Your 5 random cards:');
    for i := 0 to 4 do
        Writeln(deck[i]);
end.


{
run:

Your 5 random cards:
K of Spades
4 of Diamonds
8 of Diamonds
10 of Diamonds
8 of Clubs

}

 



answered 1 day ago by avibootz
...