5

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jonny
  • 3,022
  • 1
  • 17
  • 30

1 Answers1

9

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Boiethios
  • 38,438
  • 19
  • 134
  • 183