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

To get a sample of 5 elements from an array in Rust with replacement, you can use the rand crate to generate random indices into the array. Here's an example implementation:

main.rs
use rand::{Rng, thread_rng};

fn sample_with_replacement<T: Copy>(arr: &[T]) -> [T; 5] {
    let mut rng = thread_rng();
    let mut sample = [arr[0]; 5];
    for i in 0..5 {
        sample[i] = arr[rng.gen_range(0, arr.len())];
    }
    sample
}
248 chars
11 lines

This code creates a new thread_rng, initializes a new array called sample with the first element of the input array arr, and then generates 5 random indices into arr using rng.gen_range. These indices are used to populate sample.

Note that the type parameter T: Copy ensures that the elements of the input array are copyable, as we're copying them into the output array. If the input array isn't copyable, you might need to modify the implementation to clone elements instead.

gistlibby LogSnag