A simple wrapper to generate portably seedable pseudo-random numbers.
This library allows you to generate random numbers, with a portable and seedable generator. This means that a generator initialized with a particular seed will yield the same sequence of generated numbers on every Common Lisp implementation.
To generate a random number, you first need to create a generator object seeded with an integer:
Alternatively, you can leave out the seed, to have one generated for you:
The above will print a log message with the generator's seed value:
[INFO ] [2016-12-07 23:51:29] Random seed: 123258810179538
Once you have a generator, we can use the
GEN function to generate a number. There are a few
different methods to use for generating a number.
Generate a boolean value (T or NIL)
To generate a boolean, supply the
:BOOL keyword to
GEN, optionally with a probability for true:
(let ((generator (make-generator))) (gen :bool generator :probability 0.9))
The above will generate
T 90% of the time, and
Generate a floating-point number within a range
To generate a number that falls within a range, supply the
:RANGE keyword to
GEN like so:
(let ((generator (make-generator))) (gen :range generator :min 0.0 :max 1.0))
The above will generate a floating-point number between 0 and 10.
Generate an integer
To generate an integer within a range, supply the
:INT keyword to
(let ((generator (make-generator))) (gen :int generator :min 1 :max 100))
The above will generate an integer between 1 and 100, both inclusive. You may also tell it to
generate an odd or an even integer within this range, by using the
:PARITYP keyword as such:
(let ((generator (make-generator))) (gen :int generator :min 1 :max 100 :parityp t))
This will generate an odd integer between 1 and 100. The value of
:MIN determines the parity of
the result - a value of 2 for
:MIN would generate an even number between 2 and 100.
Choose a random element from a sequence
To choose a random element from a list or other sequence, supply the
:ELT keyword to
(let ((generator (make-generator)) (some-sequence '(1 2 3))) (gen :elt generator :sequence some-sequence))
The above will choose a random element from the sequence given.
Copyright © 2016-2018 Michael Fiano.
Licensed under the MIT License.