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

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 performs multiple draws of 5 random cards from a 52‑card deck
    WITHOUT duplicates across draws.

    It uses:
    - List<String> for the deck
    - Kotlin's built‑in 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
*/

fun buildDeck(): MutableList<String> {
    val ranks = listOf("2","3","4","5","6","7","8","9","10","J","Q","K","A")
    val suits = listOf("Clubs", "Diamonds", "Hearts", "Spades")

    val deck = mutableListOf<String>()

    for (suit in suits) {
        for (rank in ranks) {
            deck.add("$rank of $suit")
        }
    }

    return deck
}

fun drawFive(deck: MutableList<String>, drawNumber: Int) {
    // Shuffle the remaining deck before this draw
    deck.shuffle()

    println("Draw #$drawNumber:")
    deck.take(5).forEach { println("  $it") }
    println()

    // Remove drawn cards
    repeat(5) { deck.removeAt(0) }
}

fun main() {
    // Number of draws
    val numberOfDraws = 3

    val deck = buildDeck()

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

        drawFive(deck, drawIndex)
    }
}


/*
run:

Draw #1:
  J of Clubs
  9 of Hearts
  K of Hearts
  8 of Clubs
  6 of Diamonds

Draw #2:
  2 of Spades
  8 of Hearts
  2 of Clubs
  3 of Diamonds
  6 of Spades

Draw #3:
  4 of Spades
  J of Spades
  K of Clubs
  4 of Diamonds
  Q of Diamonds

*/

 



answered 4 hours ago by avibootz

Related questions

...