1

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?

2 Answers 2

1

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] } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.