Skip to main content

rand/seq/
slice.rs

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