Skip to content

Instantly share code, notes, and snippets.

@alijaya
Created December 14, 2014 20:29
Show Gist options
  • Save alijaya/1e5c83e55446d76d416f to your computer and use it in GitHub Desktop.
Save alijaya/1e5c83e55446d76d416f to your computer and use it in GitHub Desktop.
PRNG Linear Congruential Generator
/**
http://try.haxe.org/#7dB24
http://en.wikipedia.org/wiki/Linear_congruential_generator
*/
class Test {
// define the multiplier
static var a : Int = 1140671485;
// define the increment
static var c : Int = 12820163;
// define the modulo
static var m : Int = 1<<24;
// define the seed, just bash some number
static var seed : Int = 21234;
// generate random int from 0 to m
static function random() : Int
{
seed = (a * seed + c) % m;
return seed;
}
// generate random float from 0 to 1
static function randomFloat() : Float
{
return random() / m;
}
static function randomTo(to : Int) : Int
{
return Std.int(randomFloat() * to);
}
static function randomRange(from : Int, to : Int) : Int
{
return from + randomTo(to - from);
}
static function main() {
var count = 10;
// test random()
trace("random()");
for(i in 0...count) trace(random());
// test randomFloat()
trace("randomFloat()");
for(i in 0...count) trace(randomFloat());
// test randomTo(100)
trace("randomTo(100)");
for(i in 0...count) trace(randomTo(100));
// test randomRange(90, 100)
trace("randomRange(90, 100)");
for(i in 0...count) trace(randomRange(90, 100));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment