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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use super::Rng;
#[cfg(feature="std")] use std::collections::HashMap;
#[cfg(not(feature="std"))] use alloc::btree_map::BTreeMap;
#[cfg(not(feature="std"))] use alloc::Vec;
pub fn sample_iter<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Result<Vec<T>, Vec<T>>
where I: IntoIterator<Item=T>,
R: Rng,
{
let mut iter = iterable.into_iter();
let mut reservoir = Vec::with_capacity(amount);
reservoir.extend(iter.by_ref().take(amount));
if reservoir.len() == amount {
for (i, elem) in iter.enumerate() {
let k = rng.gen_range(0, i + 1 + amount);
if let Some(spot) = reservoir.get_mut(k) {
*spot = elem;
}
}
Ok(reservoir)
} else {
reservoir.shrink_to_fit();
Err(reservoir)
}
}
pub fn sample_slice<R, T>(rng: &mut R, slice: &[T], amount: usize) -> Vec<T>
where R: Rng,
T: Clone
{
let indices = sample_indices(rng, slice.len(), amount);
let mut out = Vec::with_capacity(amount);
out.extend(indices.iter().map(|i| slice[*i].clone()));
out
}
pub fn sample_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T], amount: usize) -> Vec<&'a T>
where R: Rng
{
let indices = sample_indices(rng, slice.len(), amount);
let mut out = Vec::with_capacity(amount);
out.extend(indices.iter().map(|i| &slice[*i]));
out
}
pub fn sample_indices<R>(rng: &mut R, length: usize, amount: usize) -> Vec<usize>
where R: Rng,
{
if amount > length {
panic!("`amount` must be less than or equal to `slice.len()`");
}
if amount >= length / 20 {
sample_indices_inplace(rng, length, amount)
} else {
sample_indices_cache(rng, length, amount)
}
}
fn sample_indices_inplace<R>(rng: &mut R, length: usize, amount: usize) -> Vec<usize>
where R: Rng,
{
debug_assert!(amount <= length);
let mut indices: Vec<usize> = Vec::with_capacity(length);
indices.extend(0..length);
for i in 0..amount {
let j: usize = rng.gen_range(i, length);
let tmp = indices[i];
indices[i] = indices[j];
indices[j] = tmp;
}
indices.truncate(amount);
debug_assert_eq!(indices.len(), amount);
indices
}
fn sample_indices_cache<R>(
rng: &mut R,
length: usize,
amount: usize,
) -> Vec<usize>
where R: Rng,
{
debug_assert!(amount <= length);
#[cfg(feature="std")] let mut cache = HashMap::with_capacity(amount);
#[cfg(not(feature="std"))] let mut cache = BTreeMap::new();
let mut out = Vec::with_capacity(amount);
for i in 0..amount {
let j: usize = rng.gen_range(i, length);
let tmp = match cache.get(&i) {
Some(e) => *e,
None => i,
};
let x = match cache.get(&j) {
Some(x) => *x,
None => j,
};
cache.insert(j, tmp);
out.push(x);
}
debug_assert_eq!(out.len(), amount);
out
}
#[cfg(test)]
mod test {
use super::*;
use {thread_rng, XorShiftRng, SeedableRng};
#[test]
fn test_sample_iter() {
let min_val = 1;
let max_val = 100;
let mut r = thread_rng();
let vals = (min_val..max_val).collect::<Vec<i32>>();
let small_sample = sample_iter(&mut r, vals.iter(), 5).unwrap();
let large_sample = sample_iter(&mut r, vals.iter(), vals.len() + 5).unwrap_err();
assert_eq!(small_sample.len(), 5);
assert_eq!(large_sample.len(), vals.len());
assert_eq!(large_sample, vals.iter().collect::<Vec<_>>());
assert!(small_sample.iter().all(|e| {
**e >= min_val && **e <= max_val
}));
}
#[test]
fn test_sample_slice_boundaries() {
let empty: &[u8] = &[];
let mut r = thread_rng();
assert_eq!(sample_slice(&mut r, empty, 0), vec![]);
assert_eq!(sample_slice(&mut r, &[42, 2, 42], 0), vec![]);
assert_eq!(sample_slice(&mut r, &[42], 1), vec![42]);
let v = sample_slice(&mut r, &[1, 42], 1)[0];
assert!(v == 1 || v == 42);
let v = sample_slice(&mut r, &[42, 133], 2);
assert!(v == vec![42, 133] || v == vec![133, 42]);
assert_eq!(sample_indices_inplace(&mut r, 0, 0), vec![]);
assert_eq!(sample_indices_inplace(&mut r, 1, 0), vec![]);
assert_eq!(sample_indices_inplace(&mut r, 1, 1), vec![0]);
assert_eq!(sample_indices_cache(&mut r, 0, 0), vec![]);
assert_eq!(sample_indices_cache(&mut r, 1, 0), vec![]);
assert_eq!(sample_indices_cache(&mut r, 1, 1), vec![0]);
let slice = &[42, 777];
let mut num_42 = 0;
let total = 1000;
for _ in 0..total {
let v = sample_slice(&mut r, slice, 1);
assert_eq!(v.len(), 1);
let v = v[0];
assert!(v == 42 || v == 777);
if v == 42 {
num_42 += 1;
}
}
let ratio_42 = num_42 as f64 / 1000 as f64;
assert!(0.4 <= ratio_42 || ratio_42 <= 0.6, "{}", ratio_42);
}
#[test]
fn test_sample_slice() {
let xor_rng = XorShiftRng::from_seed;
let max_range = 100;
let mut r = thread_rng();
for length in 1usize..max_range {
let amount = r.gen_range(0, length);
let seed: [u32; 4] = [
r.next_u32(), r.next_u32(), r.next_u32(), r.next_u32()
];
println!("Selecting indices: len={}, amount={}, seed={:?}", length, amount, seed);
let inplace = sample_indices_inplace(
&mut xor_rng(seed), length, amount);
let cache = sample_indices_cache(
&mut xor_rng(seed), length, amount);
assert_eq!(inplace, cache);
let regular = sample_indices(
&mut xor_rng(seed), length, amount);
assert_eq!(regular.len(), amount);
assert!(regular.iter().all(|e| *e < length));
assert_eq!(regular, inplace);
let vec: Vec<usize> = (0..length).collect();
{
let result = sample_slice(&mut xor_rng(seed), &vec, amount);
assert_eq!(result, regular);
}
{
let result = sample_slice_ref(&mut xor_rng(seed), &vec, amount);
let expected = regular.iter().map(|v| v).collect::<Vec<_>>();
assert_eq!(result, expected);
}
}
}
}