Skip to content
Snippets Groups Projects

fix random item draw

Merged STEVAN Antoine requested to merge fix-shuffle into main
use rand::{seq::SliceRandom, Rng, RngCore};
use rand::{Rng, RngCore};
use std::collections::HashSet;
#[allow(dead_code)]
fn draw_unique_indices(n: usize, vec_len: usize, rng: &mut impl RngCore) -> HashSet<usize> {
fn draw_unique_indices(n: usize, vec_len: usize, rng: &mut impl RngCore) -> Vec<usize> {
let mut indices = HashSet::new();
while indices.len() < n {
@@ -10,6 +9,8 @@ fn draw_unique_indices(n: usize, vec_len: usize, rng: &mut impl RngCore) -> Hash
indices.insert(idx);
}
let mut indices: Vec<usize> = indices.into_iter().collect();
indices.sort();
indices
}
@@ -18,8 +19,9 @@ pub(super) fn draw_unique_elements<T: Clone>(
n: usize,
rng: &mut impl RngCore,
) -> Vec<T> {
let mut things = things.to_vec();
things.shuffle(rng);
things.iter().take(n).cloned().collect()
let mut res = vec![];
for i in draw_unique_indices(n, things.len(), rng) {
res.push(things[i].clone());
}
res
}
Loading