This Rust function simulates rolling two 100-sided dice, generating two random numbers between 1 and 100 (inclusive) and returning them as a tuple. It utilizes the `rand` crate for secure random number generation.
// main.rs
// Import the 'Rng' trait from the 'rand' crate to enable random number generation.
// The 'rand' crate must be added to your Cargo.toml dependencies:
// [dependencies]
// rand = "0.8"
use rand::Rng;
/// Simulates rolling two 100-sided dice (2d100).
///
/// This function generates two independent random numbers, each ranging from 1 to 100 (inclusive).
/// It's useful for games, simulations, or any scenario requiring two separate random outcomes
/// within this specific range.
///
/// # Returns
/// A tuple `(u32, u32)` where each element represents the result of one d100 roll.
///
/// # Examples
/// ```
/// let (roll1, roll2) = roll_two_d100();
/// println!("First roll: {}, Second roll: {}", roll1, roll2);
/// assert!(roll1 >= 1 && roll1 <= 100);
/// assert!(roll2 >= 1 && roll2 <= 100);
/// ```
pub fn roll_two_d100() -> (u32, u32) {
// Create a new thread-local random number generator.
// 'thread_rng()' provides a cryptographically secure random number generator
// that is seeded by the operating system and is suitable for most use cases.
let mut rng = rand::thread_rng();
// Generate the first random number.
// 'gen_range(1..=100)' creates a uniform distribution over the range [1, 100] inclusive.
let die1 = rng.gen_range(1..=100);
// Generate the second random number, independent of the first.
let die2 = rng.gen_range(1..=100);
// Return the results as a tuple.
(die1, die2)
}
fn main() {
println!("Rolling two 100-sided dice...");
// Call the function to get the dice rolls.
let (result1, result2) = roll_two_d100();
// Print the results to the console.
println!("First die rolled: {}", result1);
println!("Second die rolled: {}", result2);
// You can also sum them up or perform other operations.
println!("Total sum: {}", result1 + result2);
}