get a sample of 5 elements from an array in rust

To get a sample of 5 elements from an array in rust, one approach is to use the rand crate to generate random indices and then select the corresponding elements from the array.

Here's an example code snippet that demonstrates this approach:

main.rs
extern crate rand;

use rand::Rng;

fn main() {
    let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    let mut rng = rand::thread_rng();

    let sample_size = 5;

    let mut sample = Vec::with_capacity(sample_size);

    while sample.len() < sample_size {
        let index = rng.gen_range(0, array.len());
        if !sample.contains(&array[index]) {
            sample.push(array[index]);
        }
    }

    println!("{:?}", sample);
}
441 chars
23 lines

In this example, we first create an array with 10 elements. We then initialize a rand::thread_rng() generator and specify the sample size as 5.

We then create an empty vector to store our sample and loop until we have sampled sample_size elements.

Inside the loop, we generate a random index using rng.gen_range() and check if the corresponding element has already been added to our sample using sample.contains(). If it hasn't, we add it to our sample vector.

Finally, we print out the resulting sample by calling println!("{:?}", sample).

gistlibby LogSnag