simplification
Download
79 lines 2.7 KiBMoonScriptModified 2026-11-08 raw
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
-- A random number generator that each Nomsu instance has its own copy of, so that one
-- instance's random numbers don't affect another's (or the program running Nomsu). It's
-- MRG32k3a (by L'Ecuyer), which uses only floating-point math, so it gives the same
-- numbers on every version of Lua. An instance can be seeded, which makes its random
-- numbers reproducible (useful for replaying a game, for example).
floor = math.floor

NORM = 2.328306549295727688e-10
M1 = 4294967087.0
M2 = 4294944443.0
A12 = 1403580.0
A13N = 810728.0
A21 = 527612.0
A23N = 1370589.0

-- Make a new generator. `seed` is an optional number; without one, the generator is
-- seeded from the current time and a counter, so separate instances differ.
_counter = 0
make_generator = (seed)->
    unless seed
        _counter += 1
        seed = os.time! * 1000 + _counter + floor(os.clock! * 1000)

    -- Spread the seed over the six state numbers, keeping each one in range and not all
    -- of either triple zero. (This uses the "minimal standard" generator, whose products
    -- stay under 2^53, so they're exact on every version of Lua.)
    s = {}
    x = floor(seed) % 2147483647
    x = 12345 if x == 0
    for i=1,6
        x = (16807 * x) % 2147483647
        s[i] = x
    s10, s11, s12 = s[1] % M1, s[2] % M1, s[3] % M1
    s20, s21, s22 = s[4] % M2, s[5] % M2, s[6] % M2
    s10 = 1 if s10 == 0 and s11 == 0 and s12 == 0
    s20 = 1 if s20 == 0 and s21 == 0 and s22 == 0

    -- Return the next number in (0, 1]
    next_number = ->
        p1 = A12 * s11 - A13N * s10
        k = floor(p1 / M1)
        p1 -= k * M1
        p1 += M1 if p1 < 0
        s10, s11, s12 = s11, s12, p1

        p2 = A21 * s22 - A23N * s20
        k = floor(p2 / M2)
        p2 -= k * M2
        p2 += M2 if p2 < 0
        s20, s21, s22 = s21, s22, p2

        return if p1 <= p2 then (p1 - p2 + M1) * NORM else (p1 - p2) * NORM

    generator = {}

    -- Like math.random: random() is a float in [0,1), random(n) is an integer in [1,n],
    -- and random(m, n) is an integer in [m, n]
    generator.random = (m, n)->
        if m == nil
            -- next_number is in (0,1]; shift to [0,1)
            return 1 - next_number!
        if n == nil
            m, n = 1, m
        m, n = floor(m), floor(n)
        error("bad argument to random (interval is empty)", 2) if m > n
        return m + floor((1 - next_number!) * (n - m + 1))

    -- Like math.randomseed
    generator.seed = (new_seed)->
        g = make_generator(new_seed)
        s10, s11, s12, s20, s21, s22 = g.state!
        return

    -- The generator's state, so one generator can copy another's
    generator.state = -> s10, s11, s12, s20, s21, s22

    return generator

return {:make_generator}