How to pick 5 random cards from a 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 picks 5 random cards from a standard 52‑card deck.

    It uses:
    - List<String> to store ranks, suits, and the deck
    - shuffled() for efficient randomization (Fisher–Yates internally)
    - Functions for clean structure and idiomatic Kotlin

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

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

    // Combine each rank with each suit → 52 unique cards
    return suits.flatMap { suit ->
        ranks.map { rank -> "$rank of $suit" }
    }
}

fun shuffleDeck(deck: List<String>): List<String> {
    // Kotlin's shuffled() uses Fisher–Yates under the hood
    return deck.shuffled()
}

fun main() {
    // Step 1: Build the deck
    val deck: List<String> = buildDeck()

    // Step 2: Shuffle the deck
    val shuffled: List<String> = shuffleDeck(deck)

    // Step 3: Draw the first 5 cards
    println("Your 5 random cards:")
    shuffled.take(5).forEach { println(it) }
}


/*
run:

Your 5 random cards:
9 of Hearts
7 of Diamonds
4 of Spades
A of Clubs
6 of Diamonds

*/

 



answered 1 day ago by avibootz
...