Login
7 branches 0 tags
Benjamin Vincent Schulenburg Even more docs 49c97ce 3 years ago 908 Commits
nujel / stdlib_modules / random.nuj
;;; Nujel - Copyright (C) 2020-2021 - Benjamin Vincent Schulenburg
;;; This project uses the MIT license, a copy should be included under /LICENSE
;;;
;;; A very simple pseudo random number generator, suitable for the illusion of
;;; randomness

[def seed 0]

[defn rng! []
      :export
      [set! seed [+ 12345 [* seed 1103515245]]]
      [bit-or [bit-shift-left [bit-and seed #xFFFF] 16]
              [bit-and [bit-shift-right seed 16] #xFFFF]]]

[defn seed! [new-seed]
      :export
      "Set a new seed value for the RNG"
      [set! seed new-seed]]

[defn seed []
      :export
      "Return the current RNG seed value"
      [return seed]]

[defn random [max]
      :export-as int
      "Return a value from 0 to MAX, or, if left out, a random int"
      [if max
          [rem [abs [rng!]] max]
          [rng!]]]

[defn seed-initialize! []
      :export
      [set! seed [bit-xor [time] [time/milliseconds]]]]
[seed-initialize!]

[deftest #t [int? [random/int]]]
[deftest #t [random/seed! 123] [def first-value [random/int]] [random/seed! 123] [= first-value [random/int]]]
[deftest #t [random/seed! 99] [not= [random/int] [random/int]]]