1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use crate::HashedPermutation;
use std::num::NonZeroU32;
pub struct HashedIter {
permutation_engine: HashedPermutation,
current_idx: u32,
}
impl HashedIter {
#[cfg(feature = "use-rand")]
pub fn new(length: NonZeroU32) -> Self {
let permutation_engine = HashedPermutation::new(length);
Self {
permutation_engine,
current_idx: 0,
}
}
pub fn new_with_seed(length: NonZeroU32, seed: u32) -> Self {
let permutation_engine = HashedPermutation::new_with_seed(length, seed);
Self {
permutation_engine,
current_idx: 0,
}
}
}
impl Iterator for HashedIter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
match self.permutation_engine.shuffle(self.current_idx) {
Ok(elem) => {
self.current_idx += 1;
Some(elem)
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashSet;
fn lengths_and_seeds() -> (Vec<NonZeroU32>, Vec<u32>) {
let lengths: Vec<NonZeroU32> = vec![100, 5, 13, 128, 249]
.iter()
.map(|&x| NonZeroU32::new(x).unwrap())
.collect();
let seeds = vec![100, 5, 13, 128, 249];
assert_eq!(lengths.len(), seeds.len());
(lengths, seeds)
}
#[test]
fn test_bijection() {
let (lengths, seeds) = lengths_and_seeds();
for (&length, seed) in lengths.iter().zip(seeds) {
let it = HashedIter::new_with_seed(length, seed);
let mut set = HashSet::new();
for elem in it {
let set_result = set.get(&elem);
assert!(set_result.is_none());
set.insert(elem);
}
let mut result: Vec<u32> = set.into_iter().collect();
result.sort();
let expected: Vec<u32> = (0..length.get()).collect();
assert_eq!(expected, result);
}
}
}