2014-01-03 13:32:13 -05:00
|
|
|
# http://coffeescriptcookbook.com/chapters/math/generating-predictable-random-numbers
|
|
|
|
class Rand
|
2014-06-30 22:16:26 -04:00
|
|
|
@className: 'Rand'
|
2014-05-15 17:54:31 -04:00
|
|
|
# If created without a seed, uses current time as seed.
|
2014-01-03 13:32:13 -05:00
|
|
|
constructor: (@seed) ->
|
|
|
|
# Knuth and Lewis' improvements to Park and Miller's LCPRNG
|
|
|
|
@multiplier = 1664525
|
|
|
|
@modulo = 4294967296 # 2**32-1
|
|
|
|
@offset = 1013904223
|
2015-01-30 11:12:34 -05:00
|
|
|
unless @seed? and 0 <= @seed < @modulo
|
2014-01-03 13:32:13 -05:00
|
|
|
@seed = (new Date().valueOf() * new Date().getMilliseconds()) % @modulo
|
|
|
|
|
2014-05-15 17:54:31 -04:00
|
|
|
# sets new seed value, even handling negative numbers
|
|
|
|
setSeed: (seed) ->
|
|
|
|
@seed = ((seed % @modulo) + @modulo) % @modulo
|
2014-01-03 13:32:13 -05:00
|
|
|
|
|
|
|
# return a random integer 0 <= n < @modulo
|
|
|
|
randn: =>
|
|
|
|
# new_seed = (a * seed + c) % m
|
|
|
|
@seed = (@multiplier * @seed + @offset) % @modulo
|
|
|
|
|
|
|
|
# return a random float 0 <= f < 1.0
|
|
|
|
randf: =>
|
|
|
|
@randn() / @modulo
|
|
|
|
|
|
|
|
# return a random int 0 <= f < n
|
|
|
|
rand: (n) =>
|
|
|
|
Math.floor @randf() * n
|
|
|
|
|
|
|
|
# return a random int min <= f < max
|
|
|
|
rand2: (min, max) =>
|
|
|
|
min + @rand max - min
|
|
|
|
|
2014-12-22 00:37:59 -05:00
|
|
|
# return a random float min <= f < max
|
|
|
|
randf2: (min, max) =>
|
|
|
|
min + @randf() * (max - min)
|
|
|
|
|
|
|
|
# return a random float within range around x
|
|
|
|
randfRange: (x, range) =>
|
|
|
|
x + (-0.5 + @randf()) * range
|
|
|
|
|
|
|
|
# shuffle array in place, and also return it
|
|
|
|
shuffle: (arr) =>
|
2015-03-06 20:35:11 -05:00
|
|
|
return arr unless arr.length > 2
|
2014-12-22 00:37:59 -05:00
|
|
|
for i in [arr.length-1 .. 1]
|
|
|
|
j = Math.floor @randf() * (i - 1)
|
|
|
|
t = arr[j]
|
|
|
|
arr[j] = arr[i]
|
|
|
|
arr[i] = t
|
|
|
|
arr
|
|
|
|
|
|
|
|
|
2014-05-15 17:54:31 -04:00
|
|
|
module.exports = Rand
|