Skip to main content

game_tree_search/mcts/
random.rs

1//! The random numbers Monte Carlo tree search draws: the [`Random`] trait and the seeded
2//! [`SplitMix64`] generator.
3
4/// A source of random bits for rollouts.
5///
6/// Implemented by [`SplitMix64`], the default. A game that needs its own generator, for
7/// example to share one sequence with the rest of a program, implements it in one line.
8pub trait Random {
9    /// The next 64 random bits.
10    fn next_u64(&mut self) -> u64;
11
12    /// A uniform index below `len`, which must not be `0`.
13    ///
14    /// Uses the remainder of a 64-bit draw, whose bias is below `len / 2^64`, too small to
15    /// matter for move choice.
16    fn below(&mut self, len: usize) -> usize {
17        let len = u64::try_from(len).expect("a slice length fits in u64");
18        usize::try_from(self.next_u64() % len).expect("an index below a length fits in usize")
19    }
20}
21
22/// The `SplitMix64` generator (Steele, Lea and Flood 2014): fast, with a full `2^64` period.
23///
24/// An own generator rather than a dependency, so a seed reproduces a search across releases.
25/// Not cryptographically secure, which rollouts do not need.
26///
27/// # Examples
28///
29/// ```
30/// use game_tree_search::{Random, SplitMix64};
31///
32/// let (mut a, mut b) = (SplitMix64::new(7), SplitMix64::new(7));
33/// assert_eq!(a.next_u64(), b.next_u64());
34/// assert!(a.below(6) < 6);
35/// ```
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct SplitMix64 {
38    /// The generator state, advanced by a fixed odd increment per draw.
39    state: u64,
40}
41
42impl SplitMix64 {
43    /// A generator from `seed`; every seed, `0` included, is valid.
44    #[must_use]
45    pub const fn new(seed: u64) -> Self {
46        Self { state: seed }
47    }
48}
49
50impl Random for SplitMix64 {
51    fn next_u64(&mut self) -> u64 {
52        self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15);
53        let mut z = self.state;
54        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
55        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
56
57        z ^ (z >> 31)
58    }
59}
60
61/// Any [`rand_core::Rng`] as a [`Random`] source, for a game that shares one generator with
62/// the rest of a program (feature `rand_core`).
63///
64/// A wrapper rather than an impl for every generator, so the feature only adds this type
65/// and never changes which generators are [`Random`].
66#[cfg(feature = "rand_core")]
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct RandCore<R>(pub R);
69
70#[cfg(feature = "rand_core")]
71impl<R: rand_core::Rng> Random for RandCore<R> {
72    fn next_u64(&mut self) -> u64 {
73        self.0.next_u64()
74    }
75}
76
77/// Unit tests for the generator.
78#[cfg(test)]
79mod tests {
80    use super::{Random, SplitMix64};
81
82    /// The first draw from seed 0 matches the published `SplitMix64` reference value.
83    #[test]
84    fn matches_the_reference_sequence() {
85        assert_eq!(SplitMix64::new(0).next_u64(), 0xe220_a839_7b1d_cdaf);
86    }
87
88    /// Indices stay below the length.
89    #[test]
90    fn indices_stay_in_range() {
91        let mut rng = SplitMix64::new(3);
92        assert!((0..1000).all(|_| rng.below(7) < 7));
93        assert_eq!(rng.below(1), 0);
94    }
95}