/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rand-0.10.2/src/seq/slice.rs
Line | Count | Source |
1 | | // Copyright 2018-2023 Developers of the Rand project. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
4 | | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
5 | | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
6 | | // option. This file may not be copied, modified, or distributed |
7 | | // except according to those terms. |
8 | | |
9 | | //! `IndexedRandom`, `IndexedMutRandom`, `SliceRandom` |
10 | | |
11 | | use super::increasing_uniform::IncreasingUniform; |
12 | | use super::index; |
13 | | #[cfg(feature = "alloc")] |
14 | | use crate::distr::uniform::{SampleBorrow, SampleUniform}; |
15 | | #[cfg(feature = "alloc")] |
16 | | use crate::distr::weighted::{Error as WeightError, Weight}; |
17 | | use crate::{Rng, RngExt}; |
18 | | use core::ops::{Index, IndexMut}; |
19 | | |
20 | | /// Extension trait on indexable lists, providing random sampling methods. |
21 | | /// |
22 | | /// This trait is implemented on `[T]` slice types. Other types supporting |
23 | | /// [`std::ops::Index<usize>`] may implement this (only [`Self::len`] must be |
24 | | /// specified). |
25 | | pub trait IndexedRandom: Index<usize> { |
26 | | /// The length |
27 | | fn len(&self) -> usize; |
28 | | |
29 | | /// True when the length is zero |
30 | | #[inline] |
31 | 0 | fn is_empty(&self) -> bool { |
32 | 0 | self.len() == 0 |
33 | 0 | } |
34 | | |
35 | | /// Uniformly sample one element |
36 | | /// |
37 | | /// Returns a reference to one uniformly-sampled random element of |
38 | | /// the slice, or `None` if the slice is empty. |
39 | | /// |
40 | | /// For slices, complexity is `O(1)`. |
41 | | /// |
42 | | /// # Example |
43 | | /// |
44 | | /// ``` |
45 | | /// use rand::seq::IndexedRandom; |
46 | | /// |
47 | | /// let choices = [1, 2, 4, 8, 16, 32]; |
48 | | /// let mut rng = rand::rng(); |
49 | | /// println!("{:?}", choices.choose(&mut rng)); |
50 | | /// assert_eq!(choices[..0].choose(&mut rng), None); |
51 | | /// ``` |
52 | 0 | fn choose<R>(&self, rng: &mut R) -> Option<&Self::Output> |
53 | 0 | where |
54 | 0 | R: Rng + ?Sized, |
55 | | { |
56 | 0 | if self.is_empty() { |
57 | 0 | None |
58 | | } else { |
59 | 0 | Some(&self[rng.random_range(..self.len())]) |
60 | | } |
61 | 0 | } |
62 | | |
63 | | /// Return an iterator which samples from `self` with replacement |
64 | | /// |
65 | | /// Returns `None` if and only if `self.is_empty()`. |
66 | | /// |
67 | | /// # Example |
68 | | /// |
69 | | /// ``` |
70 | | /// use rand::seq::IndexedRandom; |
71 | | /// |
72 | | /// let choices = [1, 2, 4, 8, 16, 32]; |
73 | | /// let mut rng = rand::rng(); |
74 | | /// for choice in choices.choose_iter(&mut rng).unwrap().take(3) { |
75 | | /// println!("{:?}", choice); |
76 | | /// } |
77 | | /// ``` |
78 | 0 | fn choose_iter<R>(&self, rng: &mut R) -> Option<impl Iterator<Item = &Self::Output>> |
79 | 0 | where |
80 | 0 | R: Rng + ?Sized, |
81 | | { |
82 | 0 | let distr = crate::distr::Uniform::new(0, self.len()).ok()?; |
83 | 0 | Some(rng.sample_iter(distr).map(|i| &self[i])) |
84 | 0 | } |
85 | | |
86 | | /// Uniformly sample `amount` distinct elements from self |
87 | | /// |
88 | | /// Chooses `amount` elements from the slice at random, without repetition, |
89 | | /// and in random order. The returned iterator is appropriate both for |
90 | | /// collection into a `Vec` and filling an existing buffer (see example). |
91 | | /// |
92 | | /// In case this API is not sufficiently flexible, use [`index::sample`]. |
93 | | /// |
94 | | /// For slices, complexity is the same as [`index::sample`]. |
95 | | /// |
96 | | /// # Example |
97 | | /// ``` |
98 | | /// use rand::seq::IndexedRandom; |
99 | | /// |
100 | | /// let mut rng = &mut rand::rng(); |
101 | | /// let sample = "Hello, audience!".as_bytes(); |
102 | | /// |
103 | | /// // collect the results into a vector: |
104 | | /// let v: Vec<u8> = sample.sample(&mut rng, 3).cloned().collect(); |
105 | | /// |
106 | | /// // store in a buffer: |
107 | | /// let mut buf = [0u8; 5]; |
108 | | /// for (b, slot) in sample.sample(&mut rng, buf.len()).zip(buf.iter_mut()) { |
109 | | /// *slot = *b; |
110 | | /// } |
111 | | /// ``` |
112 | | #[cfg(feature = "alloc")] |
113 | 0 | fn sample<R>(&self, rng: &mut R, amount: usize) -> IndexedSamples<'_, Self, Self::Output> |
114 | 0 | where |
115 | 0 | Self::Output: Sized, |
116 | 0 | R: Rng + ?Sized, |
117 | | { |
118 | 0 | let amount = core::cmp::min(amount, self.len()); |
119 | 0 | IndexedSamples { |
120 | 0 | slice: self, |
121 | 0 | _phantom: Default::default(), |
122 | 0 | indices: index::sample(rng, self.len(), amount).into_iter(), |
123 | 0 | } |
124 | 0 | } |
125 | | |
126 | | /// Uniformly sample a fixed-size array of distinct elements from self |
127 | | /// |
128 | | /// Chooses `N` elements from the slice at random, without repetition, |
129 | | /// and in random order. |
130 | | /// |
131 | | /// For slices, complexity is the same as [`index::sample_array`]. |
132 | | /// |
133 | | /// # Example |
134 | | /// ``` |
135 | | /// use rand::seq::IndexedRandom; |
136 | | /// |
137 | | /// let mut rng = &mut rand::rng(); |
138 | | /// let sample = "Hello, audience!".as_bytes(); |
139 | | /// |
140 | | /// let a: [u8; 3] = sample.sample_array(&mut rng).unwrap(); |
141 | | /// ``` |
142 | 0 | fn sample_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]> |
143 | 0 | where |
144 | 0 | Self::Output: Clone + Sized, |
145 | 0 | R: Rng + ?Sized, |
146 | | { |
147 | 0 | let indices = index::sample_array(rng, self.len())?; |
148 | 0 | Some(indices.map(|index| self[index].clone())) |
149 | 0 | } |
150 | | |
151 | | /// Biased sampling for one element |
152 | | /// |
153 | | /// Returns a reference to one element of the slice, sampled according |
154 | | /// to the provided weights. |
155 | | /// |
156 | | /// The specified function `weight` maps each item `x` to a relative |
157 | | /// likelihood `weight(x)`. The probability of each item being selected is |
158 | | /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. |
159 | | /// |
160 | | /// For slices of length `n`, complexity is `O(n)`. |
161 | | /// For more information about the underlying algorithm, |
162 | | /// see the [`WeightedIndex`] distribution. |
163 | | /// |
164 | | /// See also [`choose_weighted_mut`]. |
165 | | /// |
166 | | /// # Example |
167 | | /// |
168 | | /// ``` |
169 | | /// use rand::prelude::*; |
170 | | /// |
171 | | /// let choices = [('a', 2), ('b', 1), ('c', 1), ('d', 0)]; |
172 | | /// let mut rng = rand::rng(); |
173 | | /// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c', |
174 | | /// // and 'd' will never be printed |
175 | | /// println!("{:?}", choices.choose_weighted(&mut rng, |item| item.1).unwrap().0); |
176 | | /// ``` |
177 | | /// [`choose`]: IndexedRandom::choose |
178 | | /// [`choose_weighted_mut`]: IndexedMutRandom::choose_weighted_mut |
179 | | /// [`WeightedIndex`]: crate::distr::weighted::WeightedIndex |
180 | | #[cfg(feature = "alloc")] |
181 | 0 | fn choose_weighted<R, F, B, X>( |
182 | 0 | &self, |
183 | 0 | rng: &mut R, |
184 | 0 | weight: F, |
185 | 0 | ) -> Result<&Self::Output, WeightError> |
186 | 0 | where |
187 | 0 | R: Rng + ?Sized, |
188 | 0 | F: Fn(&Self::Output) -> B, |
189 | 0 | B: SampleBorrow<X>, |
190 | 0 | X: SampleUniform + Weight + PartialOrd<X>, |
191 | | { |
192 | | use crate::distr::weighted::WeightedIndex; |
193 | 0 | let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?; |
194 | 0 | Ok(&self[rng.sample(distr)]) |
195 | 0 | } |
196 | | |
197 | | /// Biased sampling with replacement |
198 | | /// |
199 | | /// Returns an iterator which samples elements from `self` according to the |
200 | | /// given weights with replacement (i.e. elements may be repeated). |
201 | | /// |
202 | | /// See also doc for [`Self::choose_weighted`]. |
203 | | #[cfg(feature = "alloc")] |
204 | 0 | fn choose_weighted_iter<R, F, B, X>( |
205 | 0 | &self, |
206 | 0 | rng: &mut R, |
207 | 0 | weight: F, |
208 | 0 | ) -> Result<impl Iterator<Item = &Self::Output>, WeightError> |
209 | 0 | where |
210 | 0 | R: Rng + ?Sized, |
211 | 0 | F: Fn(&Self::Output) -> B, |
212 | 0 | B: SampleBorrow<X>, |
213 | 0 | X: SampleUniform + Weight + PartialOrd<X>, |
214 | | { |
215 | | use crate::distr::weighted::WeightedIndex; |
216 | 0 | let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?; |
217 | 0 | Ok(rng.sample_iter(distr).map(|i| &self[i])) |
218 | 0 | } |
219 | | |
220 | | /// Biased sampling of `amount` distinct elements |
221 | | /// |
222 | | /// Similar to [`sample`], but where the likelihood of each |
223 | | /// element's inclusion in the output may be specified. Zero-weighted |
224 | | /// elements are never returned; the result may therefore contain fewer |
225 | | /// elements than `amount` even when `self.len() >= amount`. The elements |
226 | | /// are returned in an arbitrary, unspecified order. |
227 | | /// |
228 | | /// The specified function `weight` maps each item `x` to a relative |
229 | | /// likelihood `weight(x)`. The probability of each item being selected is |
230 | | /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. |
231 | | /// |
232 | | /// This implementation uses `O(length + amount)` space and `O(length)` time. |
233 | | /// See [`index::sample_weighted`] for details. |
234 | | /// |
235 | | /// # Example |
236 | | /// |
237 | | /// ``` |
238 | | /// use rand::prelude::*; |
239 | | /// |
240 | | /// let choices = [('a', 2), ('b', 1), ('c', 1)]; |
241 | | /// let mut rng = rand::rng(); |
242 | | /// // First Draw * Second Draw = total odds |
243 | | /// // ----------------------- |
244 | | /// // (50% * 50%) + (25% * 67%) = 41.7% chance that the output is `['a', 'b']` in some order. |
245 | | /// // (50% * 50%) + (25% * 67%) = 41.7% chance that the output is `['a', 'c']` in some order. |
246 | | /// // (25% * 33%) + (25% * 33%) = 16.6% chance that the output is `['b', 'c']` in some order. |
247 | | /// println!("{:?}", choices.sample_weighted(&mut rng, 2, |item| item.1).unwrap().collect::<Vec<_>>()); |
248 | | /// ``` |
249 | | /// [`sample`]: IndexedRandom::sample |
250 | | // Note: this is feature-gated on std due to usage of f64::powf. |
251 | | // If necessary, we may use alloc+libm as an alternative (see PR #1089). |
252 | | #[cfg(feature = "std")] |
253 | 0 | fn sample_weighted<R, F, X>( |
254 | 0 | &self, |
255 | 0 | rng: &mut R, |
256 | 0 | amount: usize, |
257 | 0 | weight: F, |
258 | 0 | ) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError> |
259 | 0 | where |
260 | 0 | Self::Output: Sized, |
261 | 0 | R: Rng + ?Sized, |
262 | 0 | F: Fn(&Self::Output) -> X, |
263 | 0 | X: Into<f64>, |
264 | | { |
265 | 0 | let amount = core::cmp::min(amount, self.len()); |
266 | | Ok(IndexedSamples { |
267 | 0 | slice: self, |
268 | 0 | _phantom: Default::default(), |
269 | 0 | indices: index::sample_weighted( |
270 | 0 | rng, |
271 | 0 | self.len(), |
272 | 0 | |idx| weight(&self[idx]).into(), |
273 | 0 | amount, |
274 | 0 | )? |
275 | 0 | .into_iter(), |
276 | | }) |
277 | 0 | } |
278 | | |
279 | | /// Deprecated: use [`Self::sample`] instead |
280 | | #[cfg(feature = "alloc")] |
281 | | #[deprecated(since = "0.10.0", note = "Renamed to `sample`")] |
282 | 0 | fn choose_multiple<R>( |
283 | 0 | &self, |
284 | 0 | rng: &mut R, |
285 | 0 | amount: usize, |
286 | 0 | ) -> IndexedSamples<'_, Self, Self::Output> |
287 | 0 | where |
288 | 0 | Self::Output: Sized, |
289 | 0 | R: Rng + ?Sized, |
290 | | { |
291 | 0 | self.sample(rng, amount) |
292 | 0 | } |
293 | | |
294 | | /// Deprecated: use [`Self::sample_array`] instead |
295 | | #[deprecated(since = "0.10.0", note = "Renamed to `sample_array`")] |
296 | 0 | fn choose_multiple_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]> |
297 | 0 | where |
298 | 0 | Self::Output: Clone + Sized, |
299 | 0 | R: Rng + ?Sized, |
300 | | { |
301 | 0 | self.sample_array(rng) |
302 | 0 | } |
303 | | |
304 | | /// Deprecated: use [`Self::sample_weighted`] instead |
305 | | #[cfg(feature = "std")] |
306 | | #[deprecated(since = "0.10.0", note = "Renamed to `sample_weighted`")] |
307 | 0 | fn choose_multiple_weighted<R, F, X>( |
308 | 0 | &self, |
309 | 0 | rng: &mut R, |
310 | 0 | amount: usize, |
311 | 0 | weight: F, |
312 | 0 | ) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError> |
313 | 0 | where |
314 | 0 | Self::Output: Sized, |
315 | 0 | R: Rng + ?Sized, |
316 | 0 | F: Fn(&Self::Output) -> X, |
317 | 0 | X: Into<f64>, |
318 | | { |
319 | 0 | self.sample_weighted(rng, amount, weight) |
320 | 0 | } |
321 | | } |
322 | | |
323 | | /// Extension trait on indexable lists, providing random sampling methods. |
324 | | /// |
325 | | /// This trait is implemented automatically for every type implementing |
326 | | /// [`IndexedRandom`] and [`std::ops::IndexMut<usize>`]. |
327 | | pub trait IndexedMutRandom: IndexedRandom + IndexMut<usize> { |
328 | | /// Uniformly sample one element (mut) |
329 | | /// |
330 | | /// Returns a mutable reference to one uniformly-sampled random element of |
331 | | /// the slice, or `None` if the slice is empty. |
332 | | /// |
333 | | /// For slices, complexity is `O(1)`. |
334 | 0 | fn choose_mut<R>(&mut self, rng: &mut R) -> Option<&mut Self::Output> |
335 | 0 | where |
336 | 0 | R: Rng + ?Sized, |
337 | | { |
338 | 0 | if self.is_empty() { |
339 | 0 | None |
340 | | } else { |
341 | 0 | let len = self.len(); |
342 | 0 | Some(&mut self[rng.random_range(..len)]) |
343 | | } |
344 | 0 | } |
345 | | |
346 | | /// Biased sampling for one element (mut) |
347 | | /// |
348 | | /// Returns a mutable reference to one element of the slice, sampled according |
349 | | /// to the provided weights. |
350 | | /// |
351 | | /// The specified function `weight` maps each item `x` to a relative |
352 | | /// likelihood `weight(x)`. The probability of each item being selected is |
353 | | /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. |
354 | | /// |
355 | | /// For slices of length `n`, complexity is `O(n)`. |
356 | | /// For more information about the underlying algorithm, |
357 | | /// see the [`WeightedIndex`] distribution. |
358 | | /// |
359 | | /// See also [`choose_weighted`]. |
360 | | /// |
361 | | /// [`choose_mut`]: IndexedMutRandom::choose_mut |
362 | | /// [`choose_weighted`]: IndexedRandom::choose_weighted |
363 | | /// [`WeightedIndex`]: crate::distr::weighted::WeightedIndex |
364 | | #[cfg(feature = "alloc")] |
365 | 0 | fn choose_weighted_mut<R, F, B, X>( |
366 | 0 | &mut self, |
367 | 0 | rng: &mut R, |
368 | 0 | weight: F, |
369 | 0 | ) -> Result<&mut Self::Output, WeightError> |
370 | 0 | where |
371 | 0 | R: Rng + ?Sized, |
372 | 0 | F: Fn(&Self::Output) -> B, |
373 | 0 | B: SampleBorrow<X>, |
374 | 0 | X: SampleUniform + Weight + PartialOrd<X>, |
375 | | { |
376 | | use crate::distr::{Distribution, weighted::WeightedIndex}; |
377 | 0 | let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?; |
378 | 0 | let index = distr.sample(rng); |
379 | 0 | Ok(&mut self[index]) |
380 | 0 | } |
381 | | } |
382 | | |
383 | | /// Extension trait on slices, providing shuffling methods. |
384 | | /// |
385 | | /// This trait is implemented on all `[T]` slice types, providing several |
386 | | /// methods for choosing and shuffling elements. You must `use` this trait: |
387 | | /// |
388 | | /// ``` |
389 | | /// use rand::seq::SliceRandom; |
390 | | /// |
391 | | /// let mut rng = rand::rng(); |
392 | | /// let mut bytes = "Hello, random!".to_string().into_bytes(); |
393 | | /// bytes.shuffle(&mut rng); |
394 | | /// let str = String::from_utf8(bytes).unwrap(); |
395 | | /// println!("{}", str); |
396 | | /// ``` |
397 | | /// Example output (non-deterministic): |
398 | | /// ```none |
399 | | /// l,nmroHado !le |
400 | | /// ``` |
401 | | pub trait SliceRandom: IndexedMutRandom { |
402 | | /// Shuffle a mutable slice in place. |
403 | | /// |
404 | | /// For slices of length `n`, complexity is `O(n)`. |
405 | | /// The resulting permutation is picked uniformly from the set of all possible permutations. |
406 | | /// |
407 | | /// # Example |
408 | | /// |
409 | | /// ``` |
410 | | /// use rand::seq::SliceRandom; |
411 | | /// |
412 | | /// let mut rng = rand::rng(); |
413 | | /// let mut y = [1, 2, 3, 4, 5]; |
414 | | /// println!("Unshuffled: {:?}", y); |
415 | | /// y.shuffle(&mut rng); |
416 | | /// println!("Shuffled: {:?}", y); |
417 | | /// ``` |
418 | | fn shuffle<R>(&mut self, rng: &mut R) |
419 | | where |
420 | | R: Rng + ?Sized; |
421 | | |
422 | | /// Sample `amount` shuffled elements |
423 | | /// |
424 | | /// Shuffles `amount` random elements into the end of the slice (`n..` where |
425 | | /// `n = self.len() - amount`). The rest of the slice (`..n`) contains the |
426 | | /// remaining elements in a permuted but not fully shuffled order. |
427 | | /// |
428 | | /// Returns a tuple of the sampled elements (`&mut self[n..]`) and the |
429 | | /// remaining elements (`&mut self[..n]`). |
430 | | /// |
431 | | /// This is an efficient method to select `amount` elements at random from |
432 | | /// the slice, provided the slice may be mutated. |
433 | | /// |
434 | | /// For slices, complexity is `O(m)` where `m = amount`. |
435 | | /// If `amount >= self.len()` this is equivalent to [`Self::shuffle`]. |
436 | | /// |
437 | | /// # Example |
438 | | /// |
439 | | /// ``` |
440 | | /// use rand::seq::SliceRandom; |
441 | | /// |
442 | | /// let mut rng = rand::rng(); |
443 | | /// let mut y = [1, 2, 3, 4, 5]; |
444 | | /// let (shuffled, rest) = y.partial_shuffle(&mut rng, 3); |
445 | | /// assert_eq!(shuffled.len(), 3); |
446 | | /// assert_eq!(rest.len(), 2); |
447 | | /// let sampled = shuffled.to_vec(); |
448 | | /// assert_eq!(&sampled, &y[2..5]); |
449 | | /// ``` |
450 | | #[must_use] |
451 | | fn partial_shuffle<R>( |
452 | | &mut self, |
453 | | rng: &mut R, |
454 | | amount: usize, |
455 | | ) -> (&mut [Self::Output], &mut [Self::Output]) |
456 | | where |
457 | | Self::Output: Sized, |
458 | | R: Rng + ?Sized; |
459 | | } |
460 | | |
461 | | impl<T> IndexedRandom for [T] { |
462 | 0 | fn len(&self) -> usize { |
463 | 0 | self.len() |
464 | 0 | } |
465 | | } |
466 | | |
467 | | impl<IR: IndexedRandom + IndexMut<usize> + ?Sized> IndexedMutRandom for IR {} |
468 | | |
469 | | impl<T> SliceRandom for [T] { |
470 | 0 | fn shuffle<R>(&mut self, rng: &mut R) |
471 | 0 | where |
472 | 0 | R: Rng + ?Sized, |
473 | | { |
474 | 0 | if self.len() <= 1 { |
475 | | // There is no need to shuffle an empty or single element slice |
476 | 0 | return; |
477 | 0 | } |
478 | 0 | let _ = self.partial_shuffle(rng, self.len()); |
479 | 0 | } |
480 | | |
481 | 0 | fn partial_shuffle<R>(&mut self, rng: &mut R, amount: usize) -> (&mut [T], &mut [T]) |
482 | 0 | where |
483 | 0 | R: Rng + ?Sized, |
484 | | { |
485 | 0 | let n = self.len().saturating_sub(amount); |
486 | | |
487 | | // The algorithm below is based on Durstenfeld's algorithm for the |
488 | | // [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) |
489 | | // for an unbiased permutation. |
490 | | // It ensures that the last `amount` elements of the slice |
491 | | // are randomly selected from the whole slice. |
492 | | |
493 | | // `IncreasingUniform::next_index()` is faster than `Rng::random_range` |
494 | | // but only works for 32 bit integers |
495 | | // So we must use the slow method if the slice is longer than that. |
496 | 0 | if self.len() < (u32::MAX as usize) { |
497 | 0 | let mut chooser = IncreasingUniform::new(rng, n as u32); |
498 | 0 | for i in n..self.len() { |
499 | 0 | let index = chooser.next_index(); |
500 | 0 | self.swap(i, index); |
501 | 0 | } |
502 | | } else { |
503 | 0 | for i in n..self.len() { |
504 | 0 | let index = rng.random_range(..i + 1); |
505 | 0 | self.swap(i, index); |
506 | 0 | } |
507 | | } |
508 | 0 | let r = self.split_at_mut(n); |
509 | 0 | (r.1, r.0) |
510 | 0 | } |
511 | | } |
512 | | |
513 | | /// An iterator over multiple slice elements. |
514 | | /// |
515 | | /// This struct is created by |
516 | | /// [`IndexedRandom::sample`](trait.IndexedRandom.html#tymethod.sample). |
517 | | #[cfg(feature = "alloc")] |
518 | | #[derive(Debug)] |
519 | | pub struct IndexedSamples<'a, S: ?Sized + 'a, T: 'a> { |
520 | | slice: &'a S, |
521 | | _phantom: core::marker::PhantomData<T>, |
522 | | indices: index::IndexVecIntoIter, |
523 | | } |
524 | | |
525 | | #[cfg(feature = "alloc")] |
526 | | impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> Iterator for IndexedSamples<'a, S, T> { |
527 | | type Item = &'a T; |
528 | | |
529 | 0 | fn next(&mut self) -> Option<Self::Item> { |
530 | | // TODO: investigate using SliceIndex::get_unchecked when stable |
531 | 0 | self.indices.next().map(|i| &self.slice[i]) |
532 | 0 | } |
533 | | |
534 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
535 | 0 | (self.indices.len(), Some(self.indices.len())) |
536 | 0 | } |
537 | | } |
538 | | |
539 | | #[cfg(feature = "alloc")] |
540 | | impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> ExactSizeIterator |
541 | | for IndexedSamples<'a, S, T> |
542 | | { |
543 | 0 | fn len(&self) -> usize { |
544 | 0 | self.indices.len() |
545 | 0 | } |
546 | | } |
547 | | |
548 | | /// Deprecated: renamed to [`IndexedSamples`] |
549 | | #[cfg(feature = "alloc")] |
550 | | #[deprecated(since = "0.10.0", note = "Renamed to `IndexedSamples`")] |
551 | | pub type SliceChooseIter<'a, S, T> = IndexedSamples<'a, S, T>; |
552 | | |
553 | | #[cfg(test)] |
554 | | mod test { |
555 | | use super::*; |
556 | | #[cfg(feature = "alloc")] |
557 | | use alloc::vec::Vec; |
558 | | |
559 | | #[test] |
560 | | fn test_slice_choose() { |
561 | | let mut r = crate::test::rng(107); |
562 | | let chars = [ |
563 | | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', |
564 | | ]; |
565 | | let mut chosen = [0i32; 14]; |
566 | | // The below all use a binomial distribution with n=1000, p=1/14. |
567 | | // binocdf(40, 1000, 1/14) ~= 2e-5; 1-binocdf(106, ..) ~= 2e-5 |
568 | | for _ in 0..1000 { |
569 | | let picked = *chars.choose(&mut r).unwrap(); |
570 | | chosen[(picked as usize) - ('a' as usize)] += 1; |
571 | | } |
572 | | for count in chosen.iter() { |
573 | | assert!(40 < *count && *count < 106); |
574 | | } |
575 | | |
576 | | chosen.iter_mut().for_each(|x| *x = 0); |
577 | | for _ in 0..1000 { |
578 | | *chosen.choose_mut(&mut r).unwrap() += 1; |
579 | | } |
580 | | for count in chosen.iter() { |
581 | | assert!(40 < *count && *count < 106); |
582 | | } |
583 | | |
584 | | let mut v: [isize; 0] = []; |
585 | | assert_eq!(v.choose(&mut r), None); |
586 | | assert_eq!(v.choose_mut(&mut r), None); |
587 | | } |
588 | | |
589 | | #[test] |
590 | | fn value_stability_slice() { |
591 | | let mut r = crate::test::rng(413); |
592 | | let chars = [ |
593 | | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', |
594 | | ]; |
595 | | let mut nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; |
596 | | |
597 | | assert_eq!(chars.choose(&mut r), Some(&'l')); |
598 | | assert_eq!(nums.choose_mut(&mut r), Some(&mut 3)); |
599 | | |
600 | | assert_eq!( |
601 | | &chars.sample_array(&mut r), |
602 | | &Some(['f', 'i', 'd', 'b', 'c', 'm', 'j', 'k']) |
603 | | ); |
604 | | |
605 | | #[cfg(feature = "alloc")] |
606 | | assert_eq!( |
607 | | &chars.sample(&mut r, 8).cloned().collect::<Vec<char>>(), |
608 | | &['h', 'm', 'd', 'b', 'c', 'e', 'n', 'f'] |
609 | | ); |
610 | | |
611 | | #[cfg(feature = "alloc")] |
612 | | assert_eq!(chars.choose_weighted(&mut r, |_| 1), Ok(&'i')); |
613 | | #[cfg(feature = "alloc")] |
614 | | assert_eq!(nums.choose_weighted_mut(&mut r, |_| 1), Ok(&mut 2)); |
615 | | |
616 | | let mut r = crate::test::rng(414); |
617 | | nums.shuffle(&mut r); |
618 | | assert_eq!(nums, [5, 11, 0, 8, 7, 12, 6, 4, 9, 3, 1, 2, 10]); |
619 | | nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; |
620 | | let res = nums.partial_shuffle(&mut r, 6); |
621 | | assert_eq!(res.0, &mut [7, 12, 6, 8, 1, 9]); |
622 | | assert_eq!(res.1, &mut [0, 11, 2, 3, 4, 5, 10]); |
623 | | } |
624 | | |
625 | | #[test] |
626 | | #[cfg_attr(miri, ignore)] // Miri is too slow |
627 | | fn test_shuffle() { |
628 | | let mut r = crate::test::rng(108); |
629 | | let empty: &mut [isize] = &mut []; |
630 | | empty.shuffle(&mut r); |
631 | | let mut one = [1]; |
632 | | one.shuffle(&mut r); |
633 | | let b: &[_] = &[1]; |
634 | | assert_eq!(one, b); |
635 | | |
636 | | let mut two = [1, 2]; |
637 | | two.shuffle(&mut r); |
638 | | assert!(two == [1, 2] || two == [2, 1]); |
639 | | |
640 | | fn move_last(slice: &mut [usize], pos: usize) { |
641 | | // use slice[pos..].rotate_left(1); once we can use that |
642 | | let last_val = slice[pos]; |
643 | | for i in pos..slice.len() - 1 { |
644 | | slice[i] = slice[i + 1]; |
645 | | } |
646 | | *slice.last_mut().unwrap() = last_val; |
647 | | } |
648 | | let mut counts = [0i32; 24]; |
649 | | for _ in 0..10000 { |
650 | | let mut arr: [usize; 4] = [0, 1, 2, 3]; |
651 | | arr.shuffle(&mut r); |
652 | | let mut permutation = 0usize; |
653 | | let mut pos_value = counts.len(); |
654 | | for i in 0..4 { |
655 | | pos_value /= 4 - i; |
656 | | let pos = arr.iter().position(|&x| x == i).unwrap(); |
657 | | assert!(pos < (4 - i)); |
658 | | permutation += pos * pos_value; |
659 | | move_last(&mut arr, pos); |
660 | | assert_eq!(arr[3], i); |
661 | | } |
662 | | for (i, &a) in arr.iter().enumerate() { |
663 | | assert_eq!(a, i); |
664 | | } |
665 | | counts[permutation] += 1; |
666 | | } |
667 | | for count in counts.iter() { |
668 | | // Binomial(10000, 1/24) with average 416.667 |
669 | | // Octave: binocdf(n, 10000, 1/24) |
670 | | // 99.9% chance samples lie within this range: |
671 | | assert!(352 <= *count && *count <= 483, "count: {}", count); |
672 | | } |
673 | | } |
674 | | |
675 | | #[test] |
676 | | fn test_partial_shuffle() { |
677 | | let mut r = crate::test::rng(118); |
678 | | |
679 | | let mut empty: [u32; 0] = []; |
680 | | let res = empty.partial_shuffle(&mut r, 10); |
681 | | assert_eq!((res.0.len(), res.1.len()), (0, 0)); |
682 | | |
683 | | let mut v = [1, 2, 3, 4, 5]; |
684 | | let res = v.partial_shuffle(&mut r, 2); |
685 | | assert_eq!((res.0.len(), res.1.len()), (2, 3)); |
686 | | assert!(res.0[0] != res.0[1]); |
687 | | // First elements are only modified if selected, so at least one isn't modified: |
688 | | assert!(res.1[0] == 1 || res.1[1] == 2 || res.1[2] == 3); |
689 | | } |
690 | | |
691 | | #[test] |
692 | | #[cfg(feature = "alloc")] |
693 | | #[cfg_attr(miri, ignore)] // Miri is too slow |
694 | | fn test_weighted() { |
695 | | let mut r = crate::test::rng(406); |
696 | | const N_REPS: u32 = 3000; |
697 | | let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; |
698 | | let total_weight = weights.iter().sum::<u32>() as f32; |
699 | | |
700 | | let verify = |result: [i32; 14]| { |
701 | | for (i, count) in result.iter().enumerate() { |
702 | | let exp = (weights[i] * N_REPS) as f32 / total_weight; |
703 | | let mut err = (*count as f32 - exp).abs(); |
704 | | if err != 0.0 { |
705 | | err /= exp; |
706 | | } |
707 | | assert!(err <= 0.25); |
708 | | } |
709 | | }; |
710 | | |
711 | | // choose_weighted |
712 | | fn get_weight<T>(item: &(u32, T)) -> u32 { |
713 | | item.0 |
714 | | } |
715 | | let mut chosen = [0i32; 14]; |
716 | | let mut items = [(0u32, 0usize); 14]; // (weight, index) |
717 | | for (i, item) in items.iter_mut().enumerate() { |
718 | | *item = (weights[i], i); |
719 | | } |
720 | | for _ in 0..N_REPS { |
721 | | let item = items.choose_weighted(&mut r, get_weight).unwrap(); |
722 | | chosen[item.1] += 1; |
723 | | } |
724 | | verify(chosen); |
725 | | |
726 | | // choose_weighted_mut |
727 | | let mut items = [(0u32, 0i32); 14]; // (weight, count) |
728 | | for (i, item) in items.iter_mut().enumerate() { |
729 | | *item = (weights[i], 0); |
730 | | } |
731 | | for _ in 0..N_REPS { |
732 | | items.choose_weighted_mut(&mut r, get_weight).unwrap().1 += 1; |
733 | | } |
734 | | for (ch, item) in chosen.iter_mut().zip(items.iter()) { |
735 | | *ch = item.1; |
736 | | } |
737 | | verify(chosen); |
738 | | |
739 | | // Check error cases |
740 | | let empty_slice = &mut [10][0..0]; |
741 | | assert_eq!( |
742 | | empty_slice.choose_weighted(&mut r, |_| 1), |
743 | | Err(WeightError::InvalidInput) |
744 | | ); |
745 | | assert_eq!( |
746 | | empty_slice.choose_weighted_mut(&mut r, |_| 1), |
747 | | Err(WeightError::InvalidInput) |
748 | | ); |
749 | | assert_eq!( |
750 | | ['x'].choose_weighted_mut(&mut r, |_| 0), |
751 | | Err(WeightError::InsufficientNonZero) |
752 | | ); |
753 | | assert_eq!( |
754 | | [0, -1].choose_weighted_mut(&mut r, |x| *x), |
755 | | Err(WeightError::InvalidWeight) |
756 | | ); |
757 | | assert_eq!( |
758 | | [-1, 0].choose_weighted_mut(&mut r, |x| *x), |
759 | | Err(WeightError::InvalidWeight) |
760 | | ); |
761 | | } |
762 | | |
763 | | #[test] |
764 | | #[cfg(feature = "std")] |
765 | | fn test_multiple_weighted_edge_cases() { |
766 | | use super::*; |
767 | | |
768 | | let mut rng = crate::test::rng(413); |
769 | | |
770 | | // Case 1: One of the weights is 0 |
771 | | let choices = [('a', 2), ('b', 1), ('c', 0)]; |
772 | | for _ in 0..100 { |
773 | | let result = choices |
774 | | .sample_weighted(&mut rng, 2, |item| item.1) |
775 | | .unwrap() |
776 | | .collect::<Vec<_>>(); |
777 | | |
778 | | assert_eq!(result.len(), 2); |
779 | | assert!(!result.iter().any(|val| val.0 == 'c')); |
780 | | } |
781 | | |
782 | | // Case 2: All of the weights are 0 |
783 | | let choices = [('a', 0), ('b', 0), ('c', 0)]; |
784 | | let r = choices.sample_weighted(&mut rng, 2, |item| item.1); |
785 | | assert_eq!(r.unwrap().len(), 0); |
786 | | |
787 | | // Case 3: Negative weights |
788 | | let choices = [('a', -1), ('b', 1), ('c', 1)]; |
789 | | let r = choices.sample_weighted(&mut rng, 2, |item| item.1); |
790 | | assert_eq!(r.unwrap_err(), WeightError::InvalidWeight); |
791 | | |
792 | | // Case 4: Empty list |
793 | | let choices = []; |
794 | | let r = choices.sample_weighted(&mut rng, 0, |_: &()| 0); |
795 | | assert_eq!(r.unwrap().count(), 0); |
796 | | |
797 | | // Case 5: NaN weights |
798 | | let choices = [('a', f64::NAN), ('b', 1.0), ('c', 1.0)]; |
799 | | let r = choices.sample_weighted(&mut rng, 2, |item| item.1); |
800 | | assert_eq!(r.unwrap_err(), WeightError::InvalidWeight); |
801 | | |
802 | | // Case 6: +infinity weights |
803 | | let choices = [('a', f64::INFINITY), ('b', 1.0), ('c', 1.0)]; |
804 | | for _ in 0..100 { |
805 | | let result = choices |
806 | | .sample_weighted(&mut rng, 2, |item| item.1) |
807 | | .unwrap() |
808 | | .collect::<Vec<_>>(); |
809 | | assert_eq!(result.len(), 2); |
810 | | assert!(result.iter().any(|val| val.0 == 'a')); |
811 | | } |
812 | | |
813 | | // Case 7: -infinity weights |
814 | | let choices = [('a', f64::NEG_INFINITY), ('b', 1.0), ('c', 1.0)]; |
815 | | let r = choices.sample_weighted(&mut rng, 2, |item| item.1); |
816 | | assert_eq!(r.unwrap_err(), WeightError::InvalidWeight); |
817 | | |
818 | | // Case 8: -0 weights |
819 | | let choices = [('a', -0.0), ('b', 1.0), ('c', 1.0)]; |
820 | | let r = choices.sample_weighted(&mut rng, 2, |item| item.1); |
821 | | assert!(r.is_ok()); |
822 | | } |
823 | | |
824 | | #[test] |
825 | | #[cfg(feature = "std")] |
826 | | #[cfg_attr(miri, ignore)] // Miri is too slow |
827 | | fn test_multiple_weighted_distributions() { |
828 | | use super::*; |
829 | | |
830 | | // The theoretical probabilities of the different outcomes are: |
831 | | // AB: 0.5 * 0.667 = 0.3333 |
832 | | // AC: 0.5 * 0.333 = 0.1667 |
833 | | // BA: 0.333 * 0.75 = 0.25 |
834 | | // BC: 0.333 * 0.25 = 0.0833 |
835 | | // CA: 0.167 * 0.6 = 0.1 |
836 | | // CB: 0.167 * 0.4 = 0.0667 |
837 | | let choices = [('a', 3), ('b', 2), ('c', 1)]; |
838 | | let mut rng = crate::test::rng(414); |
839 | | |
840 | | let mut results = [0i32; 3]; |
841 | | let expected_results = [5833, 2667, 1500]; |
842 | | for _ in 0..10000 { |
843 | | let result = choices |
844 | | .sample_weighted(&mut rng, 2, |item| item.1) |
845 | | .unwrap() |
846 | | .collect::<Vec<_>>(); |
847 | | |
848 | | assert_eq!(result.len(), 2); |
849 | | |
850 | | match (result[0].0, result[1].0) { |
851 | | ('a', 'b') | ('b', 'a') => { |
852 | | results[0] += 1; |
853 | | } |
854 | | ('a', 'c') | ('c', 'a') => { |
855 | | results[1] += 1; |
856 | | } |
857 | | ('b', 'c') | ('c', 'b') => { |
858 | | results[2] += 1; |
859 | | } |
860 | | (_, _) => panic!("unexpected result"), |
861 | | } |
862 | | } |
863 | | |
864 | | let mut diffs = results |
865 | | .iter() |
866 | | .zip(&expected_results) |
867 | | .map(|(a, b)| (a - b).abs()); |
868 | | assert!(!diffs.any(|deviation| deviation > 100)); |
869 | | } |
870 | | } |