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.rs441 chars23 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