Skip to content

Instantly share code, notes, and snippets.

@scryptonite
Last active December 16, 2015 18:40
Show Gist options
  • Save scryptonite/5479826 to your computer and use it in GitHub Desktop.
Save scryptonite/5479826 to your computer and use it in GitHub Desktop.
randomizer.js

randomizer.js

Random number generator, based on http://michalbe.blogspot.com/2011/02/javascript-random-numbers-with-custom.html

Features

  • You can serialize the state of the Randomizer for later use.
  • Keeps track of how many times .next was called on the original seed.
  • Access to the constant, prime, seed, and maximum.

Usage

var gen = new Randomizer({ seed: 1337 });
gen.next().seed; // 10954078
gen.next().seed; // 89746761091
gen.next().seed; // 735295213618600
gen.next().seed; // 709183569150976
gen.next().seed; // 697462746006528
function Randomizer(opts){
opts = opts || {};
if(!(this instanceof Randomizer)){
return new Randomizer(opts);
}
this.__opts = opts;
this.update(this.__opts);
return this;
}
Randomizer.prototype.update = function(opts){
this.seed = opts.seed || Date.now();
this.constant = opts.constant || (Math.pow(2, 13) + 1);
this.prime = opts.prime || 37;
this.maximum = opts.maximum || Math.pow(2, 50);
this.index = opts.index || 0;
return this;
}
Randomizer.prototype.reset = function(opts){
this.update(this.__opts);
return this;
}
Randomizer.prototype.next = function(){
this.seed *= this.constant;
this.seed += this.prime;
this.seed %= this.maximum;
this.index += 1;
return this;
}
Randomizer.prototype.serialize = function(){
return {
seed: this.seed,
constant: this.constant,
prime: this.prime,
maximum: this.maximum,
index: this.index
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment