rand_functors/strategies/
unique_enumerator.rs

1use std::collections::hash_map::RandomState;
2use std::collections::HashSet;
3use std::hash::BuildHasher;
4use std::marker::PhantomData;
5
6use rand::distr::uniform::SampleUniform;
7use rand::distr::StandardUniform;
8use rand::prelude::*;
9
10use crate::{
11    FlattenableRandomStrategy, Inner, RandomStrategy, RandomVariable, RandomVariableRange,
12};
13
14/// Produces all possible outputs of the random process, without repetition,
15/// stored in a [`HashSet`].
16///
17/// `UniqueEnumerator` is optimal in scenarios where certain operations will map
18/// many inputs to the same output and the user does not care about the relative
19/// frequencies of possible outputs.
20#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
21pub struct UniqueEnumerator<S: BuildHasher + Default = RandomState> {
22    phantom: PhantomData<S>,
23}
24
25impl<S: BuildHasher + Default> RandomStrategy for UniqueEnumerator<S> {
26    type Functor<I: Inner> = HashSet<I, S>;
27
28    #[inline]
29    fn fmap<A: Inner, B: Inner, F: Fn(A) -> B>(f: Self::Functor<A>, func: F) -> Self::Functor<B> {
30        f.into_iter().map(func).collect()
31    }
32
33    #[inline]
34    fn fmap_rand<A: Inner, B: Inner, R: RandomVariable, F: Fn(A, R) -> B>(
35        f: Self::Functor<A>,
36        _: &mut impl Rng,
37        func: F,
38    ) -> Self::Functor<B>
39    where
40        StandardUniform: Distribution<R>,
41    {
42        f.into_iter()
43            .flat_map(|a| R::sample_space().map(move |r| (a.clone(), r)))
44            .map(|(a, r)| func(a, r))
45            .collect()
46    }
47
48    #[inline]
49    fn fmap_rand_range<A: Inner, B: Inner, R: RandomVariable + SampleUniform, F: Fn(A, R) -> B>(
50        f: Self::Functor<A>,
51        range: impl RandomVariableRange<R>,
52        _: &mut impl Rng,
53        func: F,
54    ) -> Self::Functor<B>
55    where
56        StandardUniform: Distribution<R>,
57    {
58        f.into_iter()
59            .flat_map(|a| range.sample_space().map(move |r| (a.clone(), r)))
60            .map(|(a, r)| func(a, r))
61            .collect()
62    }
63}
64
65impl<S: BuildHasher + Default> FlattenableRandomStrategy for UniqueEnumerator<S> {
66    #[inline]
67    fn fmap_flat<A: Inner, B: Inner, F: FnMut(A) -> Self::Functor<B>>(
68        f: Self::Functor<A>,
69        func: F,
70    ) -> Self::Functor<B> {
71        f.into_iter().flat_map(func).collect()
72    }
73}