Skip to content

Instantly share code, notes, and snippets.

@laurentsenta
Created June 2, 2014 17:33
Show Gist options
  • Select an option

  • Save laurentsenta/15d7f6fcfc2987176b54 to your computer and use it in GitHub Desktop.

Select an option

Save laurentsenta/15d7f6fcfc2987176b54 to your computer and use it in GitHub Desktop.
Seedable Random Number Generator in Typescript
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)];
}
}
@jppresents
Copy link

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