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

1 Answer

0 votes
import Foundation

/*
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:
    - Array<String> for the deck
    - shuffle() for efficient randomization (Fisher–Yates internally)
    - functions for clean structure

    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
*/

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

    var deck: [String] = []

    for suit in suits {
        for rank in ranks {
            deck.append("\(rank) of \(suit)")
        }
    }

    return deck
}

func drawFive(deck: inout [String], drawNumber: Int) {
    // Shuffle the remaining deck before this draw
    deck.shuffle()

    print("Draw #\(drawNumber):")
    for card in deck.prefix(5) {
        print("  \(card)")
    }
    print()

    // Remove drawn cards
    deck.removeFirst(5)
}

func main() {
    // Number of draws
    let numberOfDraws = 3

    var deck = buildDeck()

    // Perform multiple draws (no duplicates)
    for drawIndex in 1...numberOfDraws {
        if deck.count < 5 {
            print("Not enough cards left for draw #\(drawIndex).")
            break
        }

        drawFive(deck: &deck, drawNumber: drawIndex)
    }
}

main()


/*
run:

Draw #1:
  8 of Hearts
  8 of Clubs
  2 of Hearts
  7 of Hearts
  6 of Spades

Draw #2:
  9 of Hearts
  6 of Hearts
  9 of Spades
  5 of Hearts
  Q of Diamonds

Draw #3:
  J of Hearts
  10 of Diamonds
  3 of Diamonds
  9 of Clubs
  9 of Diamonds

*/

 



answered 4 hours ago by avibootz

Related questions

...