How to select N unique random indices from an existing vector in Rust

1 Answer

0 votes
use rand::{rng, random_range};

/*
    Select N unique random indices from an existing vector in Rust.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Build a vector of indices: 0, 1, 2, ..., size-1.
    - Shuffle the indices using Fisher–Yates.
    - Take the first N shuffled indices — guaranteed unique.
    - Return those indices to the caller.
*/

/** Shuffle an index vector using Fisher–Yates */
fn shuffle_indices(indices: &mut Vec<usize>) {
    let mut _rng = rng(); // thread-local RNG (rand 0.9+)

    // Fisher–Yates shuffle
    for i in (1..indices.len()).rev() {
        // random_range returns a usize when the range is usize
        let j: usize = random_range(0..=i);
        indices.swap(i, j);
    }
}

/** Return N unique random indices */
fn pick_unique_indices(array_size: usize, count: usize) -> Vec<usize> {
    if count > array_size {
        panic!("Cannot pick more unique indices than array size.");
    }

    // Build index list
    let mut indices: Vec<usize> = (0..array_size).collect();

    // Shuffle them
    shuffle_indices(&mut indices);

    // Return first N indices
    indices[..count].to_vec()
}

fn main() {
    // Example vector
    let data: Vec<i32> = vec![5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6];

    let n: usize = 6; // number of unique indices to pick

    // Get unique random indices
    let indices: Vec<usize> = pick_unique_indices(data.len(), n);

    // Print results
    println!("Random unique indices and their values:");
    for idx in indices {
        println!("index {} -> value {}", idx, data[idx]);
    }
}


/*
run:

Random unique indices and their values:
index 15 -> value 90
index 13 -> value 74
index 4 -> value 5
index 1 -> value 12
index 14 -> value 83
index 10 -> value 17

*/

 



answered Sep 12 by avibootz

Related questions

...