shuffle an array in rust

To shuffle an array in Rust, we can use the Fisher-Yates shuffle algorithm which selects each element in the array at random and swaps it with an element that has not been selected yet.

main.rs
use rand::seq::SliceRandom;

fn shuffle_array<T>(array: &mut [T]) {
    let mut rng = rand::thread_rng();
    array.shuffle(&mut rng);
}
137 chars
7 lines

In this code, we first import the SliceRandom trait from the rand crate which provides shuffling methods for slices. Then, we define the shuffle_array function which takes a mutable reference to an array and shuffles it in place.

We create a random number generator using rand::thread_rng() and pass it to the shuffle method of the array slice. This method shuffles the elements of the slice using the Fisher-Yates algorithm.

To use this function, we can create an array and pass it to the shuffle_array function:

main.rs
fn main() {
    let mut array = [1, 2, 3, 4, 5];
    shuffle_array(&mut array);
    println!("{:?}", array);
}
111 chars
6 lines

This will output a shuffled array, e.g. [2, 3, 1, 5, 4].

gistlibby LogSnag