Skip to main content

ac_algorithm/generate/
prng.rs

1//! xorshift32 pseudo-random generator (spike #6 §2.5).
2//!
3//! ac-test seeded with `0xac7e57 ^ task.length ^ mode.length`; seeds are
4//! recorded on every generated case so runs are reproducible.
5
6/// xorshift32 state. Seed `0` is remapped because it is a fixed point.
7#[derive(Clone, Debug)]
8pub struct XorShift32 {
9    state: u32,
10}
11
12impl XorShift32 {
13    /// Creates a generator from `seed`; `0` maps to a nonzero constant.
14    #[must_use]
15    pub fn new(seed: u32) -> Self {
16        Self {
17            state: if seed == 0 { 0x9E37_79B9 } else { seed },
18        }
19    }
20
21    /// Advances the state and returns the next `u32`.
22    pub fn next_u32(&mut self) -> u32 {
23        let mut x = self.state;
24        x ^= x << 13;
25        x ^= x >> 17;
26        x ^= x << 5;
27        self.state = x;
28        x
29    }
30
31    /// Deterministic draw in `[low, high]` (inclusive). Uses a 64-bit
32    /// draw modulo the span so large ranges stay uniform-ish; the
33    /// result is exact for spans up to `u64::MAX`.
34    ///
35    /// # Panics
36    ///
37    /// Panics when `low > high` (debug assertion only in release-safe
38    /// callers — generation checks ranges first).
39    #[must_use]
40    pub fn below(&mut self, low: i64, high: i64) -> i64 {
41        debug_assert!(low <= high);
42        // Span fits u128 (≤ 2^64); the modulo result is < span ≤ 2^64,
43        // so the i128 round-trip cannot fail in practice.
44        let span = u128::try_from(i128::from(high) - i128::from(low) + 1).unwrap_or(u128::MAX);
45        let draw = (u128::from(self.next_u32()) << 32) | u128::from(self.next_u32());
46        let offset = i128::try_from(draw % span).unwrap_or(i128::MAX);
47        let value = i128::from(low) + offset;
48        i64::try_from(value).unwrap_or(low)
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn same_seed_same_sequence() {
58        let mut a = XorShift32::new(42);
59        let mut b = XorShift32::new(42);
60        for _ in 0..100 {
61            assert_eq!(a.next_u32(), b.next_u32());
62        }
63    }
64
65    #[test]
66    fn zero_seed_is_remapped() {
67        let mut rng = XorShift32::new(0);
68        assert_ne!(rng.next_u32(), 0);
69    }
70
71    #[test]
72    fn below_stays_in_range() {
73        let mut rng = XorShift32::new(7);
74        for _ in 0..1000 {
75            let v = rng.below(-5, 5);
76            assert!((-5..=5).contains(&v));
77        }
78        // Wide ranges beyond u32.
79        for _ in 0..100 {
80            let v = rng.below(-9_000_000_000, 9_000_000_000);
81            assert!((-9_000_000_000..=9_000_000_000).contains(&v));
82        }
83    }
84}