Last active
April 6, 2022 15:13
-
-
Save jprochazk/f3802cfb343b91693447a2b2ebf60ac7 to your computer and use it in GitHub Desktop.
A simple seedable PRNG
This file contains 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
// Constants from glibc (GCC), with a period of 2**31 | |
const M = (2 ** 31); | |
const A = 1103515245; | |
const C = 12345; | |
const randomSeed = (max) => Math.floor((crypto.getRandomValues(new Uint8Array(1))[0] / 255) * (max - 1)); | |
/** Linear congruential generator */ | |
class PRNG { | |
constructor(seed = randomSeed(M)) { | |
this.state = seed; | |
} | |
/** integer in range [0, 2**31) */ | |
int() { | |
this.state = (Math.imul(A, this.state) + C) & (M - 1); | |
return this.state; | |
} | |
/** float in range [0, 1] */ | |
float() { | |
return this.int() / (M - 1); | |
} | |
/** integer in range [start, end) */ | |
range(start, end) { | |
return Math.floor(this.float() * (end - start) + start) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment