hashed_permutation/
lib.rs

1//! This crate implements an algorithm that performs zero-cost permutations and shuffling on a
2//! range of numbers.
3//!
4//! This method, discovered by Andrew Kensler in 2013, uses bit-twiddling to permute a range of
5//! numbers, from `[0..n)` without needing to mutate state or store the whole range of numbers. It
6//! is extremely efficient, with no memory overhead (i.e. you don't have to store the whole range
7//! of numbers).
8//!
9//! This is effectively the same as taking some vector of numbers from `[0..n)`, randomly shuffling
10//! each element, and then calling the nth index of that vector. Kensler's algorithm offers a way
11//! to achieve the same effect, except we don't need to store a whole vector for that range of
12//! numbers.
13//!
14//! # Example Usage
15//!
16//! Using this library is fairly simple:
17//!
18//! ```rust
19//! # use hashed_permutation::HashedPermutation;
20//! use std::num::NonZeroU32;
21//!
22//! let perm = HashedPermutation {
23//!     seed: 1234,
24//!     length: NonZeroU32::new(10).unwrap(),
25//! };
26//!
27//! // Let's pick a randomly permuted number
28//! let permuted_number = perm.shuffle(0).unwrap();
29//! ```
30//!
31//! ## Iterators
32//!
33//! You can also use this structure as an iterator to iterate through a permuted set from `(0..n)`.
34//!
35//! ```rust
36//! # use hashed_permutation::HashedIter;
37//! use std::num::NonZeroU32;
38//!
39//! // Loop from (0..10) in a shuffled set
40//! let mut iterator = HashedIter::new_with_seed(NonZeroU32::new(10).unwrap(), 100);
41//!
42//! for i in iterator {
43//!     println!("{}", i);
44//! }
45//! ```
46
47mod error;
48mod iterator;
49mod kensler;
50
51pub use error::{PermutationError, PermutationResult};
52pub use iterator::HashedIter;
53pub use kensler::HashedPermutation;