Skip to main content

shuffle

Function shuffle 

Source
pub fn shuffle<T, R: Rng>(slice: &mut [T], rng: &mut R)
Expand description

Fisher-Yates (Durstenfeld) in-place shuffle.

Produces a uniformly random permutation: each of the n! permutations is equally likely.

§Algorithm

Modern variant due to Durstenfeld (1964), popularized by Knuth as “Algorithm P”. Iterates backwards, swapping each element with a uniformly chosen earlier (or same) position.

Reference: Knuth (1997), TAOCP Vol. 2, §3.4.2, Algorithm P.

§Complexity

Time: O(n), Space: O(1) (in-place)

§Examples

use u_numflow::random::{create_rng, shuffle};
let mut v = vec![1, 2, 3, 4, 5];
let mut rng = create_rng(42);
shuffle(&mut v, &mut rng);
// v is now a permutation of [1, 2, 3, 4, 5]
v.sort();
assert_eq!(v, vec![1, 2, 3, 4, 5]);