Arcade.Rng
Types
Functions
fn next_unit(n : Arcade.Numerics.Numerics, r : Rng) : (Float, Rng) needs () do let (v, after) = next(r) let top53 = v.hi 2097152 + int_shr(v.lo, 11) (int_to_float(top53) . n.unit53, after) end
-- r * 2 + bit, modulo n, for r < n, without ever exceeding n. Long division -- by doubling keeps a bound near 2^53 exact on the JS target. pfn shift_in(r : Int, bit : Int, n : Int) : Int needs () do let doubled = if r >= n - r do r - (n - r) else r + r end if bit == 0 do doubled else if doubled == n - 1 do 0 else doubled + 1 end end end
pfn divide_word(r : Int, word : Int, position : Int, n : Int) : Int needs () do if position < 0 do r else divide_word(shift_in(r, int_and(int_shr(word, position), 1), n), word, position - 1, n) end end
-- v % n. With n <= 2^20 two exact steps do it; beyond that, bit by bit. pfn mod_int(v : U64, n : { Int | _ > 0 }) : Int needs () do if n <= 1048576 do (v.hi % n * 4294967296 + v.lo) % n else divide_word(divide_word(0, v.hi, 31, n), v.lo, 31, n) end end
fn next_gaussian(n : Arcade.Numerics.Numerics, r : Rng) : (Float, Rng) needs () do let (first, r1) = next_unit(n, r) let u1 = Arcade.Num.max_float(first, n.floor_u1) let (u2, r2) = next_unit(n, r1) (Math.sqrt(-2.0 . Math.log(u1)) . Math.cos(n.tau *. u2), r2) end
pfn replace_at(xs : List(a), i : Int, x : a) : List(a) needs () do List.append(List.take(xs, i), Cons(x, List.drop(xs, i + 1))) end
pfn swap_at(xs : List(a), i : Int, j : Int) : List(a) needs () do match (List.nth_opt(xs, i), List.nth_opt(xs, j)) do (Some(at_i), Some(at_j)) -> replace_at(replace_at(xs, i, at_j), j, at_i) (None, _) -> xs (_, None) -> xs end end
pfn shuffle_down(r : Rng, xs : List(a), i : Int) : (List(a), Rng) needs () do if i <= 0 do (xs, r) else do let (j, after) = next_int_below(r, i + 1) shuffle_down(after, swap_at(xs, i, j), i - 1) end end end