Created
June 2, 2014 17:33
-
-
Save laurentsenta/15d7f6fcfc2987176b54 to your computer and use it in GitHub Desktop.
Seedable Random Number Generator in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class RNG { | |
| private seed:number; | |
| constructor(seed:number) { | |
| this.seed = seed; | |
| } | |
| private next(min:number, max:number):number { | |
| max = max || 0; | |
| min = min || 0; | |
| this.seed = (this.seed * 9301 + 49297) % 233280; | |
| var rnd = this.seed / 233280; | |
| return min + rnd * (max - min); | |
| } | |
| // http://indiegamr.com/generate-repeatable-random-numbers-in-js/ | |
| public nextInt(min:number, max:number):number { | |
| return Math.round(this.next(min, max)); | |
| } | |
| public nextDouble():number { | |
| return this.next(0, 1); | |
| } | |
| public pick(collection:any[]):any { | |
| return collection[this.nextInt(0, collection.length - 1)]; | |
| } | |
| } |
When changing to floor, you also have to change pick (remove the -1):
public pick(collection:any[]):any {
return collection[this.nextInt(0, collection.length)];
}
otherwhise the last element is never picked, because max is no longer inclusive.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In reference to @makoConstruct suggestions:
I ran a quick test to check distribution after this change:
which results in values:
(Similar tests with different seeds and ranges also produced reasonable looking distributions)
EDIT: I recommend throwing an 'abs' in for the seed too, I think negative seed values might mess up the algebra