如何从元素向量创建随机样本?
How to create a random sample from a vector of elements?
我使用此代码为数字 0 到 49 创建了一个随机样本。现在我想为一组自定义值创建一个随机样本。例如:select 来自 [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);
}
听起来你可以使用 permutate crate 中的排列:
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");
}
}
}
您可以使用 IteratorRandom
to get a much shorter solution. This is an extension trait for iterators, it offers convenience functions such as choose_multiple
and choose_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);
}
我使用此代码为数字 0 到 49 创建了一个随机样本。现在我想为一组自定义值创建一个随机样本。例如:select 来自 [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);
}
听起来你可以使用 permutate crate 中的排列:
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");
}
}
}
您可以使用 IteratorRandom
to get a much shorter solution. This is an extension trait for iterators, it offers convenience functions such as choose_multiple
and choose_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);
}