我有一个向量,其中元素是(String, String)
。我如何随机选择其中一个元素?
use rand::seq::SliceRandom; // 0.6.5
fn main() {
let samples = vec!["hi", "this", "is", "a", "test!"];
let sample: Vec<_> = samples
.choose_multiple(&mut rand::thread_rng(), 1)
.collect();
println!("{:?}", sample);
}
如果您想选择多个元素,则可能是适合您的crate random_choice:
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);
}
}
加密采样的另一个选择是已经包含在rand
箱中的是WeightedIndex
,它有一个例子:
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); }