Small library for generating random permutations of the set {0, ..., n-1} where n is a product of small prime powers, with much less than O(n) memory usage.
Thinking of a permutation as a function σ
from {0, ..., n-1} to itself, this library also allows for computation of σ(i)
and σ^(-1)(i)
in constant time (independent of i
).
First n
is factored into prime powers, and random permutations of {0, ..., q-1} are generated for each prime power q
in the factorization of n
. Then the Chinese Remainder Theorem is used to combine each combination of elements from these "sub-permutations" into a permutation of {0, ..., n-1}.
Don't use this if you need any of the following:
n
. You can use the Composition
struct to compose multiple permutations which can reduce the chance of this happening.```rust // Create a permutation on 11! points. let factorial11 = (1..=11).product(); let perm = RandomPermutation::new(factorial11).unwrap();
// Calculate the image of 0, 1, 2, ..., 99 under the permutation.
let image = perm.iter().take(100).collect::
// Find i
such that the image of i
is 0.
let i = perm.inverse().nth(0).unwrap();
assert_eq!(perm.nth(i), Some(0));
```