Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to sample N elements from array in Rust

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading