use super::increasing_uniform::IncreasingUniform;
use super::index;
#[cfg(feature = "alloc")]
use crate::distr::uniform::{SampleBorrow, SampleUniform};
#[cfg(feature = "alloc")]
use crate::distr::weighted::{Error as WeightError, Weight};
use crate::{Rng, RngExt};
use core::ops::{Index, IndexMut};
pub trait IndexedRandom: Index<usize> {
fn len(&self) -> usize;
#[inline]
fn is_empty(&self) -> bool {
self.len() == 0
}
fn choose<R>(&self, rng: &mut R) -> Option<&Self::Output>
where
R: Rng + ?Sized,
{
if self.is_empty() {
None
} else {
Some(&self[rng.random_range(..self.len())])
}
}
fn choose_iter<R>(&self, rng: &mut R) -> Option<impl Iterator<Item = &Self::Output>>
where
R: Rng + ?Sized,
{
let distr = crate::distr::Uniform::new(0, self.len()).ok()?;
Some(rng.sample_iter(distr).map(|i| &self[i]))
}
#[cfg(feature = "alloc")]
fn sample<R>(&self, rng: &mut R, amount: usize) -> IndexedSamples<'_, Self, Self::Output>
where
Self::Output: Sized,
R: Rng + ?Sized,
{
let amount = core::cmp::min(amount, self.len());
IndexedSamples {
slice: self,
_phantom: Default::default(),
indices: index::sample(rng, self.len(), amount).into_iter(),
}
}
fn sample_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]>
where
Self::Output: Clone + Sized,
R: Rng + ?Sized,
{
let indices = index::sample_array(rng, self.len())?;
Some(indices.map(|index| self[index].clone()))
}
#[cfg(feature = "alloc")]
fn choose_weighted<R, F, B, X>(
&self,
rng: &mut R,
weight: F,
) -> Result<&Self::Output, WeightError>
where
R: Rng + ?Sized,
F: Fn(&Self::Output) -> B,
B: SampleBorrow<X>,
X: SampleUniform + Weight + PartialOrd<X>,
{
use crate::distr::weighted::WeightedIndex;
let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?;
Ok(&self[rng.sample(distr)])
}
#[cfg(feature = "alloc")]
fn choose_weighted_iter<R, F, B, X>(
&self,
rng: &mut R,
weight: F,
) -> Result<impl Iterator<Item = &Self::Output>, WeightError>
where
R: Rng + ?Sized,
F: Fn(&Self::Output) -> B,
B: SampleBorrow<X>,
X: SampleUniform + Weight + PartialOrd<X>,
{
use crate::distr::weighted::WeightedIndex;
let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?;
Ok(rng.sample_iter(distr).map(|i| &self[i]))
}
#[cfg(feature = "std")]
fn sample_weighted<R, F, X>(
&self,
rng: &mut R,
amount: usize,
weight: F,
) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError>
where
Self::Output: Sized,
R: Rng + ?Sized,
F: Fn(&Self::Output) -> X,
X: Into<f64>,
{
let amount = core::cmp::min(amount, self.len());
Ok(IndexedSamples {
slice: self,
_phantom: Default::default(),
indices: index::sample_weighted(
rng,
self.len(),
|idx| weight(&self[idx]).into(),
amount,
)?
.into_iter(),
})
}
#[cfg(feature = "alloc")]
#[deprecated(since = "0.10.0", note = "Renamed to `sample`")]
fn choose_multiple<R>(
&self,
rng: &mut R,
amount: usize,
) -> IndexedSamples<'_, Self, Self::Output>
where
Self::Output: Sized,
R: Rng + ?Sized,
{
self.sample(rng, amount)
}
#[deprecated(since = "0.10.0", note = "Renamed to `sample_array`")]
fn choose_multiple_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]>
where
Self::Output: Clone + Sized,
R: Rng + ?Sized,
{
self.sample_array(rng)
}
#[cfg(feature = "std")]
#[deprecated(since = "0.10.0", note = "Renamed to `sample_weighted`")]
fn choose_multiple_weighted<R, F, X>(
&self,
rng: &mut R,
amount: usize,
weight: F,
) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError>
where
Self::Output: Sized,
R: Rng + ?Sized,
F: Fn(&Self::Output) -> X,
X: Into<f64>,
{
self.sample_weighted(rng, amount, weight)
}
}
pub trait IndexedMutRandom: IndexedRandom + IndexMut<usize> {
fn choose_mut<R>(&mut self, rng: &mut R) -> Option<&mut Self::Output>
where
R: Rng + ?Sized,
{
if self.is_empty() {
None
} else {
let len = self.len();
Some(&mut self[rng.random_range(..len)])
}
}
#[cfg(feature = "alloc")]
fn choose_weighted_mut<R, F, B, X>(
&mut self,
rng: &mut R,
weight: F,
) -> Result<&mut Self::Output, WeightError>
where
R: Rng + ?Sized,
F: Fn(&Self::Output) -> B,
B: SampleBorrow<X>,
X: SampleUniform + Weight + PartialOrd<X>,
{
use crate::distr::{Distribution, weighted::WeightedIndex};
let distr = WeightedIndex::new((0..self.len()).map(|idx| weight(&self[idx])))?;
let index = distr.sample(rng);
Ok(&mut self[index])
}
}
pub trait SliceRandom: IndexedMutRandom {
fn shuffle<R>(&mut self, rng: &mut R)
where
R: Rng + ?Sized;
fn partial_shuffle<R>(
&mut self,
rng: &mut R,
amount: usize,
) -> (&mut [Self::Output], &mut [Self::Output])
where
Self::Output: Sized,
R: Rng + ?Sized;
}
impl<T> IndexedRandom for [T] {
fn len(&self) -> usize {
self.len()
}
}
impl<IR: IndexedRandom + IndexMut<usize> + ?Sized> IndexedMutRandom for IR {}
impl<T> SliceRandom for [T] {
fn shuffle<R>(&mut self, rng: &mut R)
where
R: Rng + ?Sized,
{
if self.len() <= 1 {
return;
}
self.partial_shuffle(rng, self.len());
}
fn partial_shuffle<R>(&mut self, rng: &mut R, amount: usize) -> (&mut [T], &mut [T])
where
R: Rng + ?Sized,
{
let m = self.len().saturating_sub(amount);
if self.len() < (u32::MAX as usize) {
let mut chooser = IncreasingUniform::new(rng, m as u32);
for i in m..self.len() {
let index = chooser.next_index();
self.swap(i, index);
}
} else {
for i in m..self.len() {
let index = rng.random_range(..i + 1);
self.swap(i, index);
}
}
let r = self.split_at_mut(m);
(r.1, r.0)
}
}
#[cfg(feature = "alloc")]
#[derive(Debug)]
pub struct IndexedSamples<'a, S: ?Sized + 'a, T: 'a> {
slice: &'a S,
_phantom: core::marker::PhantomData<T>,
indices: index::IndexVecIntoIter,
}
#[cfg(feature = "alloc")]
impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> Iterator for IndexedSamples<'a, S, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.indices.next().map(|i| &self.slice[i])
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.indices.len(), Some(self.indices.len()))
}
}
#[cfg(feature = "alloc")]
impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> ExactSizeIterator
for IndexedSamples<'a, S, T>
{
fn len(&self) -> usize {
self.indices.len()
}
}
#[cfg(feature = "alloc")]
#[deprecated(since = "0.10.0", note = "Renamed to `IndexedSamples`")]
pub type SliceChooseIter<'a, S, T> = IndexedSamples<'a, S, T>;
#[cfg(test)]
mod test {
use super::*;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[test]
fn test_slice_choose() {
let mut r = crate::test::rng(107);
let chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
];
let mut chosen = [0i32; 14];
for _ in 0..1000 {
let picked = *chars.choose(&mut r).unwrap();
chosen[(picked as usize) - ('a' as usize)] += 1;
}
for count in chosen.iter() {
assert!(40 < *count && *count < 106);
}
chosen.iter_mut().for_each(|x| *x = 0);
for _ in 0..1000 {
*chosen.choose_mut(&mut r).unwrap() += 1;
}
for count in chosen.iter() {
assert!(40 < *count && *count < 106);
}
let mut v: [isize; 0] = [];
assert_eq!(v.choose(&mut r), None);
assert_eq!(v.choose_mut(&mut r), None);
}
#[test]
fn value_stability_slice() {
let mut r = crate::test::rng(413);
let chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
];
let mut nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
assert_eq!(chars.choose(&mut r), Some(&'l'));
assert_eq!(nums.choose_mut(&mut r), Some(&mut 3));
assert_eq!(
&chars.sample_array(&mut r),
&Some(['f', 'i', 'd', 'b', 'c', 'm', 'j', 'k'])
);
#[cfg(feature = "alloc")]
assert_eq!(
&chars.sample(&mut r, 8).cloned().collect::<Vec<char>>(),
&['h', 'm', 'd', 'b', 'c', 'e', 'n', 'f']
);
#[cfg(feature = "alloc")]
assert_eq!(chars.choose_weighted(&mut r, |_| 1), Ok(&'i'));
#[cfg(feature = "alloc")]
assert_eq!(nums.choose_weighted_mut(&mut r, |_| 1), Ok(&mut 2));
let mut r = crate::test::rng(414);
nums.shuffle(&mut r);
assert_eq!(nums, [5, 11, 0, 8, 7, 12, 6, 4, 9, 3, 1, 2, 10]);
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let res = nums.partial_shuffle(&mut r, 6);
assert_eq!(res.0, &mut [7, 12, 6, 8, 1, 9]);
assert_eq!(res.1, &mut [0, 11, 2, 3, 4, 5, 10]);
}
#[test]
#[cfg_attr(miri, ignore)] fn test_shuffle() {
let mut r = crate::test::rng(108);
let empty: &mut [isize] = &mut [];
empty.shuffle(&mut r);
let mut one = [1];
one.shuffle(&mut r);
let b: &[_] = &[1];
assert_eq!(one, b);
let mut two = [1, 2];
two.shuffle(&mut r);
assert!(two == [1, 2] || two == [2, 1]);
fn move_last(slice: &mut [usize], pos: usize) {
let last_val = slice[pos];
for i in pos..slice.len() - 1 {
slice[i] = slice[i + 1];
}
*slice.last_mut().unwrap() = last_val;
}
let mut counts = [0i32; 24];
for _ in 0..10000 {
let mut arr: [usize; 4] = [0, 1, 2, 3];
arr.shuffle(&mut r);
let mut permutation = 0usize;
let mut pos_value = counts.len();
for i in 0..4 {
pos_value /= 4 - i;
let pos = arr.iter().position(|&x| x == i).unwrap();
assert!(pos < (4 - i));
permutation += pos * pos_value;
move_last(&mut arr, pos);
assert_eq!(arr[3], i);
}
for (i, &a) in arr.iter().enumerate() {
assert_eq!(a, i);
}
counts[permutation] += 1;
}
for count in counts.iter() {
assert!(352 <= *count && *count <= 483, "count: {}", count);
}
}
#[test]
fn test_partial_shuffle() {
let mut r = crate::test::rng(118);
let mut empty: [u32; 0] = [];
let res = empty.partial_shuffle(&mut r, 10);
assert_eq!((res.0.len(), res.1.len()), (0, 0));
let mut v = [1, 2, 3, 4, 5];
let res = v.partial_shuffle(&mut r, 2);
assert_eq!((res.0.len(), res.1.len()), (2, 3));
assert!(res.0[0] != res.0[1]);
assert!(res.1[0] == 1 || res.1[1] == 2 || res.1[2] == 3);
}
#[test]
#[cfg(feature = "alloc")]
#[cfg_attr(miri, ignore)] fn test_weighted() {
let mut r = crate::test::rng(406);
const N_REPS: u32 = 3000;
let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7];
let total_weight = weights.iter().sum::<u32>() as f32;
let verify = |result: [i32; 14]| {
for (i, count) in result.iter().enumerate() {
let exp = (weights[i] * N_REPS) as f32 / total_weight;
let mut err = (*count as f32 - exp).abs();
if err != 0.0 {
err /= exp;
}
assert!(err <= 0.25);
}
};
fn get_weight<T>(item: &(u32, T)) -> u32 {
item.0
}
let mut chosen = [0i32; 14];
let mut items = [(0u32, 0usize); 14]; for (i, item) in items.iter_mut().enumerate() {
*item = (weights[i], i);
}
for _ in 0..N_REPS {
let item = items.choose_weighted(&mut r, get_weight).unwrap();
chosen[item.1] += 1;
}
verify(chosen);
let mut items = [(0u32, 0i32); 14]; for (i, item) in items.iter_mut().enumerate() {
*item = (weights[i], 0);
}
for _ in 0..N_REPS {
items.choose_weighted_mut(&mut r, get_weight).unwrap().1 += 1;
}
for (ch, item) in chosen.iter_mut().zip(items.iter()) {
*ch = item.1;
}
verify(chosen);
let empty_slice = &mut [10][0..0];
assert_eq!(
empty_slice.choose_weighted(&mut r, |_| 1),
Err(WeightError::InvalidInput)
);
assert_eq!(
empty_slice.choose_weighted_mut(&mut r, |_| 1),
Err(WeightError::InvalidInput)
);
assert_eq!(
['x'].choose_weighted_mut(&mut r, |_| 0),
Err(WeightError::InsufficientNonZero)
);
assert_eq!(
[0, -1].choose_weighted_mut(&mut r, |x| *x),
Err(WeightError::InvalidWeight)
);
assert_eq!(
[-1, 0].choose_weighted_mut(&mut r, |x| *x),
Err(WeightError::InvalidWeight)
);
}
#[test]
#[cfg(feature = "std")]
fn test_multiple_weighted_edge_cases() {
use super::*;
let mut rng = crate::test::rng(413);
let choices = [('a', 2), ('b', 1), ('c', 0)];
for _ in 0..100 {
let result = choices
.sample_weighted(&mut rng, 2, |item| item.1)
.unwrap()
.collect::<Vec<_>>();
assert_eq!(result.len(), 2);
assert!(!result.iter().any(|val| val.0 == 'c'));
}
let choices = [('a', 0), ('b', 0), ('c', 0)];
let r = choices.sample_weighted(&mut rng, 2, |item| item.1);
assert_eq!(r.unwrap().len(), 0);
let choices = [('a', -1), ('b', 1), ('c', 1)];
let r = choices.sample_weighted(&mut rng, 2, |item| item.1);
assert_eq!(r.unwrap_err(), WeightError::InvalidWeight);
let choices = [];
let r = choices.sample_weighted(&mut rng, 0, |_: &()| 0);
assert_eq!(r.unwrap().count(), 0);
let choices = [('a', f64::NAN), ('b', 1.0), ('c', 1.0)];
let r = choices.sample_weighted(&mut rng, 2, |item| item.1);
assert_eq!(r.unwrap_err(), WeightError::InvalidWeight);
let choices = [('a', f64::INFINITY), ('b', 1.0), ('c', 1.0)];
for _ in 0..100 {
let result = choices
.sample_weighted(&mut rng, 2, |item| item.1)
.unwrap()
.collect::<Vec<_>>();
assert_eq!(result.len(), 2);
assert!(result.iter().any(|val| val.0 == 'a'));
}
let choices = [('a', f64::NEG_INFINITY), ('b', 1.0), ('c', 1.0)];
let r = choices.sample_weighted(&mut rng, 2, |item| item.1);
assert_eq!(r.unwrap_err(), WeightError::InvalidWeight);
let choices = [('a', -0.0), ('b', 1.0), ('c', 1.0)];
let r = choices.sample_weighted(&mut rng, 2, |item| item.1);
assert!(r.is_ok());
}
#[test]
#[cfg(feature = "std")]
fn test_multiple_weighted_distributions() {
use super::*;
let choices = [('a', 3), ('b', 2), ('c', 1)];
let mut rng = crate::test::rng(414);
let mut results = [0i32; 3];
let expected_results = [5833, 2667, 1500];
for _ in 0..10000 {
let result = choices
.sample_weighted(&mut rng, 2, |item| item.1)
.unwrap()
.collect::<Vec<_>>();
assert_eq!(result.len(), 2);
match (result[0].0, result[1].0) {
('a', 'b') | ('b', 'a') => {
results[0] += 1;
}
('a', 'c') | ('c', 'a') => {
results[1] += 1;
}
('b', 'c') | ('c', 'b') => {
results[2] += 1;
}
(_, _) => panic!("unexpected result"),
}
}
let mut diffs = results
.iter()
.zip(&expected_results)
.map(|(a, b)| (a - b).abs());
assert!(!diffs.any(|deviation| deviation > 100));
}
}