Rust 如何从向量或数组中随机选择一个元素?

Rust 如何从向量或数组中随机选择一个元素?,rust,Rust,我有一个向量,其中元素是(String,String)。我怎样才能随机选择其中一个元素?您想要板条箱,特别是方法 如果您想选择多个元件,则板条箱可能适合您: extern crate random_choice; use self::random_choice::random_choice; fn main() { let mut samples = vec!["hi", "this", "is", "a"

我有一个向量,其中元素是
(String,String)
。我怎样才能随机选择其中一个元素?

您想要板条箱,特别是方法


如果您想选择多个元件,则板条箱可能适合您:

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);
    }
}
外部板条箱随机选择;
使用self::random\u choice::random\u choice;
fn main(){
让mut samples=vec![“hi”,“this”,“is”,“a”,“test!”];
让权重:Vec=Vec![5.6,7.8,9.7,1.1,2.0];
设选择数=100;
let choices=random_choice().random_choice_f64(样本和权重,数字选择);
选择中的选择{
打印!(“{}”,选项);
}
}
使用:

使用rand::seq::SliceRandom;//0.7.2
fn main(){
让samples=vec![“hi”,“this”,“is”,“a”,“test!”];
让样本:Vec=样本
。选择多线程(&mut rand::thread\u rng(),1)
.收集();
println!(“{:?}”,样本);
}

另一种加权取样选择已包含在
兰德
板条箱中,例如:


如果您还想删除所选元素,这里有一种方法(使用
rand
板条箱):

让mut vec=vec![0,1,2,3,4,5,6,7,8,9];
让index=(rand::random::()*vec.len()作为f32.floor()作为usize;
让值=向量移除(索引);
普林顿!((“索引:{}值:{}”,索引,值);
普林顿!(“{:?}”,vec);


remove(index)
删除
index
处的值(将其后面的所有元素向左移动),并返回
index
()处的值。

获取随机元素的方法太复杂了:(我不同意。这种方法与其他语言的唯一区别是需要将trait放入范围内,并手动指定rng状态的来源。可能比通常更明确一些,但我觉得可以。
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);
    }
}
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);
}
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);
}
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);