Add SliceRandom trait for shuffling slices using RNG

This commit is contained in:
Palash Tyagi 2025-07-28 20:17:35 +01:00
parent d0b0f295b1
commit 6fd796cceb

16
src/random/seq.rs Normal file
View File

@ -0,0 +1,16 @@
use crate::random::Rng;
/// Trait for randomizing slices.
pub trait SliceRandom {
/// Shuffle the slice in place using the provided RNG.
fn shuffle<R: Rng>(&mut self, rng: &mut R);
}
impl<T> SliceRandom for [T] {
fn shuffle<R: Rng>(&mut self, rng: &mut R) {
for i in (1..self.len()).rev() {
let j = rng.random_range(0..(i + 1));
self.swap(i, j);
}
}
}