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

1 Answer

0 votes
/*
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:
    - [String] arrays to store ranks, suits, and the deck
    - shuffled() for efficient randomization (Fisher–Yates internally)
    - Functions for clean structure and idiomatic Swift

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

func buildDeck() -> [String] {
    let ranks: [String] = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"]
    let suits: [String] = ["Clubs", "Diamonds", "Hearts", "Spades"]

    // Combine each rank with each suit → 52 unique cards
    var deck: [String] = []
    for suit in suits {
        for rank in ranks {
            deck.append("\(rank) of \(suit)")
        }
    }

    return deck
}

func shuffleDeck(_ deck: [String]) -> [String] {
    // Swift's shuffled() uses Fisher–Yates under the hood
    return deck.shuffled()
}

func main() {
    // Step 1: Build the deck
    let deck: [String] = buildDeck()

    // Step 2: Shuffle the deck
    let shuffled: [String] = shuffleDeck(deck)

    // Step 3: Draw the first 5 cards
    print("Your 5 random cards:")
    for i in 0..<5 {
        print(shuffled[i])
    }
}

main()


/*
run:

Your 5 random cards:
4 of Spades
K of Diamonds
6 of Diamonds
J of Diamonds
K of Hearts

*/

 



answered 1 day ago by avibootz
...