Roger V.
Roger V.

Reputation: 706

Sampling with replacement in Rust

The following snippet samples elements with replacement from a vector:

use rand::seq::IteratorRandom;

fn main() {
    let mut rng = rand::rng();
    let values = vec![1, 2, 3, 4, 5] as Vec<i32>;
    let mut samples = Vec::new();
    for _ in 1..10 {
        let v = values.iter().choose(&mut rng).unwrap();
        samples.push(v);
    }
    println!("{:?}", samples);
}

Is there a more idiomatic/Rustic way of achieving the same thing?

Related: How to create a random sample from a vector of elements?

Upvotes: 1

Views: 39

Answers (2)

BallpointBen
BallpointBen

Reputation: 13857

This uses IndexRandom to sample from a Vec (or anything that derefs into a slice).

use rand::seq::IndexedRandom;

fn main() {
    let mut rng = rand::rng();
    let values = vec![1_i32, 2, 3, 4, 5];
    let samples = (0..10)
        .map(|_| values.choose(&mut rng).unwrap())
        .collect::<Vec<_>>();

    println!("{:?}", samples);
    // [2, 4, 5, 1, 2, 2, 2, 3, 4, 2]
}

Upvotes: 1

Roger V.
Roger V.

Reputation: 706

My own answer which produces the same effect is:

use rand::seq::IteratorRandom;

fn main() {
    let mut rng = rand::rng();
    let values = vec![1, 2, 3, 4, 5] as Vec<i32>;
    let samples: Vec<_> = (1..10).map(|_| *values.iter().choose(&mut rng).unwrap()).collect();
    println!("{:?}", samples);
}

Remark: I am not however sure how to fix the seed to have exactly reproducible results.

Upvotes: 0

Related Questions