Skip to main content

SliceRandom

Trait SliceRandom 

Source
pub trait SliceRandom: IndexedMutRandom {
    // Required methods
    fn shuffle<R>(&mut self, rng: &mut R)
       where R: Rng + ?Sized;
    fn partial_shuffle<R>(
        &mut self,
        rng: &mut R,
        amount: usize,
    ) -> (&mut [Self::Output], &mut [Self::Output])
       where Self::Output: Sized,
             R: Rng + ?Sized;
}
Expand description

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§

Source

fn shuffle<R>(&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);
Source

fn partial_shuffle<R>( &mut self, rng: &mut R, amount: usize, ) -> (&mut [Self::Output], &mut [Self::Output])
where Self::Output: Sized, R: Rng + ?Sized,

Sample amount shuffled elements

Shuffles amount random elements into the end of the slice (n.. where n = self.len() - amount). The rest of the slice (..n) contains the remaining elements in a permuted but not fully shuffled order.

Returns a tuple of the sampled elements (&mut self[n..]) and the remaining elements (&mut self[..n]).

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

For slices, complexity is O(m) where m = amount. If amount >= self.len() this is equivalent to Self::shuffle.

§Example
use rand::seq::SliceRandom;

let mut rng = rand::rng();
let mut y = [1, 2, 3, 4, 5];
let (shuffled, rest) = y.partial_shuffle(&mut rng, 3);
assert_eq!(shuffled.len(), 3);
assert_eq!(rest.len(), 2);
let sampled = shuffled.to_vec();
assert_eq!(&sampled, &y[2..5]);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> SliceRandom for [T]

Source§

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

Source§

fn partial_shuffle<R>( &mut self, rng: &mut R, amount: usize, ) -> (&mut [T], &mut [T])
where R: Rng + ?Sized,

Implementors§