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

1 Answer

0 votes
use rand::seq::SliceRandom; // shuffle
use rand::rng;              // thread-local random generator (rand 0.9+)

/*
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:
    - Vec<String> for the deck
    - SliceRandom::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
*/

fn build_deck() -> Vec<String> {
    let ranks = vec![
        "2","3","4","5","6","7","8","9","10","J","Q","K","A"
    ];
    let suits = vec![
        "Clubs", "Diamonds", "Hearts", "Spades"
    ];

    let mut deck = Vec::with_capacity(52);

    for suit in suits {
        for rank in &ranks {
            deck.push(format!("{} of {}", rank, suit));
        }
    }

    deck
}

fn draw_five(deck: &mut Vec<String>, draw_number: usize) {
    // Shuffle the remaining deck before this draw
    let mut rng = rng();
    deck.shuffle(&mut rng);

    println!("Draw #{}:", draw_number);
    for card in deck.iter().take(5) {
        println!("  {}", card);
    }
    println!();

    // Remove drawn cards
    deck.drain(0..5);
}

fn main() {
    // Number of draws
    let number_of_draws = 3;

    let mut deck = build_deck();

    // Perform multiple draws (no duplicates)
    for draw_index in 1..=number_of_draws {
        if deck.len() < 5 {
            println!("Not enough cards left for draw #{}.", draw_index);
            break;
        }

        draw_five(&mut deck, draw_index);
    }
}


/*
run:

Draw #1:
  6 of Hearts
  7 of Diamonds
  K of Diamonds
  10 of Clubs
  2 of Diamonds

Draw #2:
  3 of Spades
  K of Hearts
  2 of Hearts
  5 of Hearts
  8 of Hearts

Draw #3:
  9 of Spades
  J of Spades
  3 of Clubs
  9 of Hearts
  Q of Diamonds

*/

 



answered 4 hours ago by avibootz

Related questions

...