Skip to content

shuffle

Returns the elements in a random order (Fisher–Yates: every permutation is equally likely), leaving items as it is.

The order depends only on the generator, so the same seed always gives the same result.

use helpers4::random::shuffle;

Cargo feature random (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features random

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.9", default-features = false, features = ["random"] }
pub fn shuffle<T: Clone>(items: &[T], rng: &mut Rng) -> Vec<T>
ParameterTypeDescription
items&[T]The elements to shuffle.
rng&mut RngThe generator that decides the order.

Vec<T> — A new Vec with the same elements in a random order.

use helpers4::random::{shuffle, Rng};

let deck = [1, 2, 3, 4, 5];
let first = shuffle(&deck, &mut Rng::seeded(7));
let again = shuffle(&deck, &mut Rng::seeded(7));
assert_eq!(first, again); // reproducible

let mut sorted = first.clone();
sorted.sort_unstable();
assert_eq!(sorted, deck); // nothing lost, nothing added

src/random/shuffle.rs