rust 如何从元素向量创建随机样本?

uqxowvwt  于 2022-12-19  发布在  其他
关注(0)|答案(2)|浏览(139)

我使用这段代码为数字0到49创建了一个随机样本。现在我想为一组自定义值创建一个随机样本。例如:从[1, 2, 3, 4, 9, 10, 11, 14, 16, 22, 32, 45]中选择5个样本。如何执行此操作?

use rand::{seq, thread_rng}; // 0.7.3

fn main() {
    let mut rng = thread_rng();
    let sample = seq::index::sample(&mut rng, 50, 5);
}
w8f9ii69

w8f9ii691#

你可以使用IteratorRandom来得到一个更短的解,这是迭代器的一个扩展特性,它提供了choose_multiplechoose_multiple_fill这样方便的函数:

use rand::{seq::IteratorRandom, thread_rng}; // 0.6.1

fn main() {
    let mut rng = thread_rng();
    let v = vec![1, 2, 3, 4, 5];
    let sample = v.iter().choose_multiple(&mut rng, 2);

    println!("{:?}", sample);
}
2hh7jdfx

2hh7jdfx2#

听起来像是可以使用permutate机箱中的排列:

extern crate permutate; // 0.3.2

use permutate::Permutator;
use std::io::{self, Write};

fn main() {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let list: &[&str] = &["one", "two", "three", "four"];
    let list = [list];
    let mut permutator = Permutator::new(&list[..]);

    if let Some(mut permutation) = permutator.next() {
        for element in &permutation {
            let _ = stdout.write(element.as_bytes());
        }
        let _ = stdout.write(b"\n");
        while permutator.next_with_buffer(&mut permutation) {
            for element in &permutation {
                let _ = stdout.write(element.as_bytes());
            }
            let _ = stdout.write(b"\n");
        }
    }
}

相关问题