Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle an array deterministically with a seed?

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.

like image 688
jonny Avatar asked May 01 '18 15:05

jonny


People also ask

How do I shuffle NumPy array with seed?

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.

How do you shuffle data in an array?

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] // ...

How do you shuffle items in an array Python?

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.


1 Answers

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.

like image 143
Boiethios Avatar answered Oct 11 '22 14:10

Boiethios