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.rs248 chars11 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