I'm finding it difficult to shuffle an array deterministically, i.e. with a random seed in Rust. What I'm trying to achieve (in pseudo code):
let v = vec![0, 1, 2, 3];
pseudo_shuffle(v, randomSeed1) // always produces e.g. [3,1,2,0]
pseudo_shuffle(v, randomSeed2) // always produces e.g. [0,2,3,1]
In another Stack Overflow answer I learnt how to use rand::Rng::shuffle()
to shuffle a vector non-deterministically, but it doesn't seem to provide an API for applying a random seed to the generation function, and I'm having a difficult time coming up with a solution myself that doesn't employ some ridiculous n!
complexity algorithm.
NumPy random seed shuffle You can shuffle the sequence of numbers using NumPy random. shuffle(). Using shuffle without using seed, it shuffles the sequence randomly, every time we execute the command. With the same seed value, you can shuffle the sequence in a particular order, every time we execute the command.
Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...
Using shuffle() method from Random library to shuffle the given array. Here we are using shuffle method from the built-in random module to shuffle the entire array at once.
Use a random number generator that implements the trait SeedableRng
and call from_seed
with the desired seed.
Example:
use rand::{seq::SliceRandom, SeedableRng}; // 0.6.5
use rand_chacha::ChaChaRng; // 0.1.1
fn main() {
let seed = [0; 32];
let mut rng = ChaChaRng::from_seed(seed);
let mut v1 = vec![1, 2, 3, 4, 5];
v1.shuffle(&mut rng);
assert_eq!(v1, [3, 5, 2, 4, 1]);
}
Clone the RNG before using it or create a new one from scratch with the same seed to reset back to the original state.
You may also be interested in ReseedingRng
as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With