I have a vector where the element is a (String, String)
. How can I randomly pick one of these elements?
Element access:reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.
1 Answer. There could be many ways to randomly select elements from an R vector. You can use the sample() or the runif() function to select elements from the vector.
To generate the random values between 0 and n-1 , we can use the cstdlib's functions rand() and srand() or use any of the standard generators defined in the <random> header introduced in C++11.
You want the rand
crate, specifically the choose
method.
use rand::seq::SliceRandom; // 0.7.2
fn main() {
let vs = vec![0, 1, 2, 3, 4];
println!("{:?}", vs.choose(&mut rand::thread_rng()));
}
Using choose_multiple
:
use rand::seq::SliceRandom; // 0.7.2
fn main() {
let samples = vec!["hi", "this", "is", "a", "test!"];
let sample: Vec<_> = samples
.choose_multiple(&mut rand::thread_rng(), 1)
.collect();
println!("{:?}", sample);
}
Another choice for weighted sampling that is already included in the rand
crate is WeightedIndex
, which has an example:
use rand::prelude::*; use rand::distributions::WeightedIndex; let choices = ['a', 'b', 'c']; let weights = [2, 1, 1]; let dist = WeightedIndex::new(&weights).unwrap(); let mut rng = thread_rng(); for _ in 0..100 { // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' println!("{}", choices[dist.sample(&mut rng)]); } let items = [('a', 0), ('b', 3), ('c', 7)]; let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap(); for _ in 0..100 { // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' println!("{}", items[dist2.sample(&mut rng)].0); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With