Generate Random Values

Generate random numbers

rand cat-algorithms cat-no-std

Generates random numbers with help of the random-number generator rand::Rng. Each thread has an initialized generator. Integers are uniformly distributed over the range of the type, and floating point numbers are uniformly distributed from 0 up to but not including 1.


// In `Cargo.toml`
// rand = "0.8.5"
// or
// rand = { version = "0.9.0-beta.3", features = [ "thread_rng" ] }

fn main() {
    let n1: u8 = rand::random();
    let n2: u16 = rand::random();
    println!("Random u8: {}", n1);
    println!("Random u16: {}", n2);
    println!("Random u32: {}", rand::random::<u32>());
    println!("Random i32: {}", rand::random::<i32>());
    println!("Random float: {}", rand::random::<f64>());
}

Generate random numbers within a range

rand cat-algorithms cat-no-std

Generates a random value within half-open [0, 10) range (not including 10) with rand::Rng::gen_range⮳ range.

use rand::Rng;

fn main() {
    let mut rng = rand::rng();
    println!("Integer: {}", rng.random_range(0..10));
    println!("Float: {}", rng.random_range(0.0..10.0));
}

rand::distributions::uniform::Uniform can obtain values with uniform distribution. This has the same effect, but may be faster when repeatedly generating numbers in the same range.

use rand::distr::Distribution;
use rand::distr::Uniform;

fn main() {
    let mut rng = rand::rng();
    let die = Uniform::try_from(1..7).unwrap();

    loop {
        let throw = die.sample(&mut rng);
        println!("Roll the die: {}", throw);
        if throw == 6 {
            break;
        }
    }
}

Generate random numbers within a given distribution

rand rand_distr cat-algorithms cat-no-std

By default, random numbers in the rand⮳ crate have uniform distribution⮳. The rand_distr⮳ crate provides other kinds of distributions. To use them, you instantiate a distribution, then sample from that distribution using rand::distributions::Distribution::sample⮳ with help of a random-number generator rand::Rng⮳. The distributions available are documented here⮳. An example using the rand_distr::Normal⮳ distribution is shown below.

// use rand::distr::Distribution;
// use rand_distr::Normal;
// use rand_distr::NormalError;

// fn main() -> Result<(), NormalError> {
//     let mut rng = rand::rng();
//     let normal = Normal::new(2.0, 3.0)?;
//     let v = normal.sample(&mut rng);
//     println!("{} is from a N(2, 9) distribution", v);
//     Ok(())
// }

Generate random values of a custom type

rand cat-algorithms cat-no-std

Randomly generates a tuple (i32, bool, f64) and variable of user defined type Point. Implements the rand::distributions::Distribution⮳ trait on type Point for rand::distributions::Standard⮳ trait in order to allow random generation.

use rand::Rng;
use rand::distr::Distribution;
use rand::distr::StandardUniform;

#[derive(Debug)]
#[allow(dead_code)]
struct Point {
    x: i32,
    y: i32,
}

// Required by:
// pub fn random<T>() -> T
// where
//     StandardUniform: Distribution<T>,
impl Distribution<Point> for StandardUniform {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point {
        let (x, y) = rng.random::<(i32, i32)>();
        Point { x, y }
    }
}

fn main() {
    let mut rng = rand::rng();
    let rand_tuple = rng.random::<(i32, bool, f64)>();
    println!("Random tuple: {:?}", rand_tuple);

    let rand_point: Point = rng.random();
    println!("Random Point: {:?}", rand_point);
}

Create random passwords from a set of alphanumeric characters

rand cat-algorithms

Randomly generates a string of given length ASCII characters in the range A-Z, a-z, 0-9, with rand::distributions::Alphanumeric⮳ sample.

use rand::Rng;
use rand::distr::Alphanumeric;
use rand::rng;

fn main() {
    let rand_string: String = rng()
        .sample_iter(&Alphanumeric)
        .take(30)
        .map(char::from)
        .collect();
    println!("{}", rand_string);
}

Create random passwords from a set of user-defined characters

rand cat-os

Randomly generates a string of given length ASCII characters with custom user-defined bytestring, with rand::Rng::gen_range.

#![allow(deprecated)]

fn main() {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                            abcdefghijklmnopqrstuvwxyz\
                            0123456789)(*&^%$#@!~";
    const PASSWORD_LEN: usize = 30;

    let password: String = (0..PASSWORD_LEN)
        .map(|_| {
            let idx = rand::random_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect();

    println!("{:?}", password);
}