Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to sample N elements from array

Tags:

random

std

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.

like image 450
winwin Avatar asked Dec 05 '25 06:12

winwin


2 Answers

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

like image 164
Jmb Avatar answered Dec 06 '25 18:12

Jmb


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

like image 40
Netwave Avatar answered Dec 06 '25 18:12

Netwave