get a sample of 5 elements from an array without replacement in rust

To get a sample of 5 elements without replacement from an array in Rust, we can use the rand crate and its seq::index::sample method. Here's an example:

main.rs
use rand::seq::index::sample;
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let sample = sample(&mut rng, array.len(), 5);

    let mut result = Vec::new();
    for i in sample {
        result.push(array[i]);
    }

    println!("{:?}", result); // prints something like [7, 9, 2, 5, 8]
}
363 chars
16 lines

Here, we first create an array with 10 integers. Then, we use the sample function to generate a sample of 5 indices without replacement, using the length of the array as the population size. Finally, we create a new vector and populate it with the elements of the array at the sampled indices. The resulting vector contains the 5 randomly sampled elements from the array.

gistlibby LogSnag