I have a vector where the element is a (String, String)
. How can I randomly pick one of these elements?
6 Answers
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()));
}
-
11I'd disagree. The only differences with this approach and other languages are the need to put the trait in scope and manually needing to specify where the rng state comes from. Perhaps a tad more explicit than usual, but I find it okay. Mar 19, 2020 at 0:50
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 want to choose more than one element then the random_choice crate may be right for you:
extern crate random_choice;
use self::random_choice::random_choice;
fn main() {
let mut samples = vec!["hi", "this", "is", "a", "test!"];
let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0];
let number_choices = 100;
let choices = random_choice().random_choice_f64(&samples, &weights, number_choices);
for choice in choices {
print!("{}, ", choice);
}
}
If you also want to remove the chosen element, here's one way to do that (using the rand
crate):
let mut vec = vec![0,1,2,3,4,5,6,7,8,9];
let index = (rand::random::<f32>() * vec.len() as f32).floor() as usize;
let value = vec.remove( index );
println!("index: {} value: {}", index, value);
println!("{:?}", vec);
remove(index)
removes that value at index
(shifting all the elements after it to the left) and the returns the value that was at index
(docs).
Another way of getting a random value is via the indexing method using rng.gen_range and vec.get(). This also prevents the borrowing of the value (which occurs with the vec.choose() method)
fn main() {
let mut rng = rand::thread_rng();
let my_strings : Vec<&str> = vec!["a", "b", "c"];
let random_string_index: usize = rng.gen_range(0..my_strings.len());
let string = my_strings[random_string_index];
println!("{:?}", string);
}