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.rs137 chars7 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.rs111 chars6 lines
This will output a shuffled array, e.g. [2, 3, 1, 5, 4]
.
gistlibby LogSnag