Shuffle
Uniformly random permutation of sample using generator .
- Algorithm — Fisher-Yates (Knuth shuffle), see Shuffle
- Complexity — time, space (returns new array)
- Output — new array (does not modify input)
Properties
- Uniformity each of permutations has equal probability
- Determinism same generator state produces same permutation
Example
Rng("demo-shuffle").Shuffle([1, 2, 3, 4, 5])— shuffled copyr.Shuffle(x)preserves multiset (same elements, different order)
Implementation names
| Language | Method |
|---|---|
| C# | Rng.Shuffle() |
| Go | Shuffle() |
| Kotlin | Rng.shuffle() |
| Rust | Rng::shuffle() |
| Python | Rng.shuffle() |
| R | rng$shuffle() |
| TypeScript | Rng.shuffle() |
produces a random reordering of data. This is essential for permutation tests and useful for eliminating any bias from the original ordering. Every possible arrangement has exactly equal probability, which is required for valid statistical inference. The function returns a new shuffled array and leaves the original data unchanged. For reproducible results, pass a seeded generator: Shuffle(data, Rng("experiment-1")) will always produce the same permutation.
Algorithm
The function uses the Fisher-Yates algorithm (see Fisher & Yates 1938, Knuth 1997), also known as the Knuth shuffle, with the Rng generator for random decisions:
for i from n-1 down to 1:
j = uniform_int(0, i+1)
swap(array[i], array[j])
This produces a uniformly random permutation in time with additional space (the input is copied). The algorithm is unbiased: each of the permutations has equal probability.
Tests
The test suite contains 12 test cases validating random permutation. Given a seed and input array , returns a permutation of using the FisherYates algorithm. All tests verify reproducibility: the same seed and input must produce the same permutation across all language implementations.
Seed variation (, ) 3 tests with different seeds:
seed-0-n5-basic: seedseed-123-n5-basic: seedseed-999-n5-basic: seed
These tests validate that different seeds produce different permutations of the same input.
Fixed seed (seed ) 9 tests exploring different input sizes and content:
seed-1729-n1-single: (trivial case, single element)seed-1729-n2-basic: (minimum non-trivial case)seed-1729-n5-basic: (standard case)seed-1729-n5-zeros: (all identical, permutation preserves content)seed-1729-n6-neg: (negative and positive values)seed-1729-n10-seq: (10-element sequential)seed-1729-n20-seq: (20-element sequential)seed-1729-n100-seq: (large array)seed-123-n10-seq: seed , (different seed, same size as n10-seq)
The progression from to validates that the FisherYates implementation scales correctly. The zero-valued and negative-valued tests verify that shuffling operates on positions, not values.