ac-algorithm 0.2.0

Algorithm competition domain logic for ac
Documentation
//! xorshift32 pseudo-random generator (spike #6 §2.5).
//!
//! ac-test seeded with `0xac7e57 ^ task.length ^ mode.length`; seeds are
//! recorded on every generated case so runs are reproducible.

/// xorshift32 state. Seed `0` is remapped because it is a fixed point.
#[derive(Clone, Debug)]
pub struct XorShift32 {
    state: u32,
}

impl XorShift32 {
    /// Creates a generator from `seed`; `0` maps to a nonzero constant.
    #[must_use]
    pub fn new(seed: u32) -> Self {
        Self {
            state: if seed == 0 { 0x9E37_79B9 } else { seed },
        }
    }

    /// Advances the state and returns the next `u32`.
    pub fn next_u32(&mut self) -> u32 {
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        self.state = x;
        x
    }

    /// Deterministic draw in `[low, high]` (inclusive). Uses a 64-bit
    /// draw modulo the span so large ranges stay uniform-ish; the
    /// result is exact for spans up to `u64::MAX`.
    ///
    /// # Panics
    ///
    /// Panics when `low > high` (debug assertion only in release-safe
    /// callers — generation checks ranges first).
    #[must_use]
    pub fn below(&mut self, low: i64, high: i64) -> i64 {
        debug_assert!(low <= high);
        // Span fits u128 (≤ 2^64); the modulo result is < span ≤ 2^64,
        // so the i128 round-trip cannot fail in practice.
        let span = u128::try_from(i128::from(high) - i128::from(low) + 1).unwrap_or(u128::MAX);
        let draw = (u128::from(self.next_u32()) << 32) | u128::from(self.next_u32());
        let offset = i128::try_from(draw % span).unwrap_or(i128::MAX);
        let value = i128::from(low) + offset;
        i64::try_from(value).unwrap_or(low)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn same_seed_same_sequence() {
        let mut a = XorShift32::new(42);
        let mut b = XorShift32::new(42);
        for _ in 0..100 {
            assert_eq!(a.next_u32(), b.next_u32());
        }
    }

    #[test]
    fn zero_seed_is_remapped() {
        let mut rng = XorShift32::new(0);
        assert_ne!(rng.next_u32(), 0);
    }

    #[test]
    fn below_stays_in_range() {
        let mut rng = XorShift32::new(7);
        for _ in 0..1000 {
            let v = rng.below(-5, 5);
            assert!((-5..=5).contains(&v));
        }
        // Wide ranges beyond u32.
        for _ in 0..100 {
            let v = rng.below(-9_000_000_000, 9_000_000_000);
            assert!((-9_000_000_000..=9_000_000_000).contains(&v));
        }
    }
}