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

1 Answer

0 votes
import scala.util.Random

/*
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
    - Random.shuffle for efficient randomization
    - Pure functions for clarity and idiomatic Scala

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

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

  // Combine each rank with each suit → 52 unique cards
  for {
    suit <- suits
    rank <- ranks
  } yield s"$rank of $suit"
}

def shuffleDeck(deck: List[String]): List[String] = {
  // Random.shuffle uses Fisher–Yates internally
  Random.shuffle(deck)
}

def main(args: Array[String]): Unit = {
  // 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)
}


/*
run:

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

*/

 



answered 1 day ago by avibootz
...