Search code examples
rustsample

How to create a random sample from a vector of elements?


I used this code to create a random sample for the numbers 0 to 49. Now I want to create a random sample for a custom set of values. For example: select a sample of 5 from [1, 2, 3, 4, 9, 10, 11, 14, 16, 22, 32, 45]. How can I do this?

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

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

Solution

  • Sounds like you can use a permutation from the 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");
            }
        }
    }