mirror of
https://github.com/Magnus167/rustframe.git
synced 2025-08-20 04:00:01 +00:00
Add SliceRandom trait for shuffling slices using RNG
This commit is contained in:
parent
d0b0f295b1
commit
6fd796cceb
16
src/random/seq.rs
Normal file
16
src/random/seq.rs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user