Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created May 10, 2022 16:21
Show Gist options
  • Save redblobgames/2a48f1b55528a3c23b3824a9a3314fa4 to your computer and use it in GitHub Desktop.
Save redblobgames/2a48f1b55528a3c23b3824a9a3314fa4 to your computer and use it in GitHub Desktop.
sfc32 random number generator, typescript
// SFC32 random number generator, public domain code adapted
// from https://github.com/bryc/code/blob/master/jshash/PRNGs.md
function PRNG(seed: number): {
nextInt(): number;
nextFloat(): number;
getState(): number[];
setState(state: number[]): void
} {
let a = 0, b = seed, c = 0, d = 1;
function sfc32() {
a |= 0; b |= 0; c |= 0; d |= 0;
var t = (a + b | 0) + d | 0;
d = d + 1 | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = c << 21 | c >>> 11;
c = c + t | 0;
return t >>> 0;
};
for (let i = 0; i < 12; i++) sfc32(); // scramble the seed
return {
nextInt: sfc32,
nextFloat() { return sfc32() / 4294967296; },
getState() { return [a, b, c, d]; },
setState(state: number[]) { [a, b, c, d] = state; },
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment