Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to pick 5 random cards from a 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 picks 5 random cards from a standard 52-card deck.
It uses:
- Vec<String> for the deck
- SliceRandom::shuffle for efficient randomization
- rand::rng() as the high-quality, thread-local random source
*/

// Builds a standard 52-card deck as a vector of "Rank of Suit" strings.
fn build_deck() -> Vec<String> {
    // Ranks and suits of a standard deck
    let ranks = [
        "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A",
    ];
    let suits = ["Clubs", "Diamonds", "Hearts", "Spades"];

    let mut deck = Vec::with_capacity(52); // Efficient: avoid reallocations

    // Build the deck: 13 ranks x 4 suits
    for suit in suits {
        for rank in ranks {
            deck.push(format!("{} of {}", rank, suit));
        }
    }
    deck
}

fn main() {
    // Build the deck
    let mut deck = build_deck();

    // Thread-local random generator, seeded securely by the OS
    let mut rand_gen = rng();

    // Shuffle the whole deck in place (Fisher-Yates, O(n))
    deck.shuffle(&mut rand_gen);

    // Draw the first 5 cards
    println!("Your 5 random cards:");
    for card in deck.iter().take(5) {
        println!("{}", card);
    }
}


/* 
run:

Your 5 random cards:
10 of Clubs
Q of Diamonds
3 of Clubs
Q of Clubs
K of Spades

*/

 



answered Jul 4 by avibootz
edited Jul 4 by avibootz
...