Trait SliceRandom

trait SliceRandom: IndexedMutRandom

Extension trait on slices, providing shuffling methods.

This trait is implemented on all [T] slice types, providing several methods for choosing and shuffling elements. You must use this trait:

use rand::seq::SliceRandom;

let mut rng = rand::rng();
let mut bytes = "Hello, random!".to_string().into_bytes();
bytes.shuffle(&mut rng);
let str = String::from_utf8(bytes).unwrap();
println!("{}", str);

Example output (non-deterministic):

l,nmroHado !le

Required Methods

fn shuffle<R>(self: &mut Self, rng: &mut R)
where
    R: Rng + ?Sized

Shuffle a mutable slice in place.

For slices of length n, complexity is O(n). The resulting permutation is picked uniformly from the set of all possible permutations.

Example

use rand::seq::SliceRandom;

let mut rng = rand::rng();
let mut y = [1, 2, 3, 4, 5];
println!("Unshuffled: {:?}", y);
y.shuffle(&mut rng);
println!("Shuffled:   {:?}", y);
fn partial_shuffle<R>(self: &mut Self, rng: &mut R, amount: usize) -> (&mut [<Self as >::Output], &mut [<Self as >::Output])
where
    <Self as >::Output: Sized,
    R: Rng + ?Sized

Shuffle a slice in place, but exit early.

Returns two mutable slices from the source slice. The first contains amount elements randomly permuted. The second has the remaining elements that are not fully shuffled.

This is an efficient method to select amount elements at random from the slice, provided the slice may be mutated.

If you only need to choose elements randomly and amount > self.len()/2 then you may improve performance by taking amount = self.len() - amount and using only the second slice.

If amount is greater than the number of elements in the slice, this will perform a full shuffle.

For slices, complexity is O(m) where m = amount.

Implementors