Suppose we have an array:
let arr: [u8; 10] = [1,2,3,4,5,6,7,8,9,10];
Is there a function in Rust to choose N random elements from it without repetitions? Equivalent to python's random.sample function.
You can use choose_multiple:
use rand::prelude::*;
fn main() {
let mut rng = rand::thread_rng();
let arr: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sample: Vec<_> = arr.choose_multiple (&mut rng, 3).collect();
println!("{:?}", sample);
}
Playground
You can use sample for getting a sample over indexes, then just iterate and get those from the original array:
use rand::prelude::*;
use rand::seq::index::sample;
fn main() {
let mut rng = rand::thread_rng();
let arr: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sample: Vec<u8> = sample(&mut rng, arr.len(), 3)
.iter()
.map(|i| arr[i])
.collect();
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With