Skip to content

Instantly share code, notes, and snippets.

@ooflorent
Created July 19, 2018 07:28
Show Gist options
  • Save ooflorent/410d10aff04bd5b260cbb566d5858971 to your computer and use it in GitHub Desktop.
Save ooflorent/410d10aff04bd5b260cbb566d5858971 to your computer and use it in GitHub Desktop.
Simple PRNG
let rng = createNumberGenerator(
createSeedFromString("Hello friends!") // 2053374269
);
// Generate a boolean with 30% success
console.log(generateBoolean(rng, 0.3)); // false
console.log(generateBoolean(rng, 0.3)); // true
// Generate a D6
console.log(generateNumber(rng, 1, 6)); // 3
console.log(generateNumber(rng, 1, 6)); // 5
console.log(generateNumber(rng, 1, 6)); // 5
// Generate a float between 0 and 1
console.log(generateFloat(rng)); // 0.4461949771377712
console.log(generateFloat(rng)); // 0.22262383583528544
function toUint32(x) {
return x >>> 0;
}
function createSeedFromString(string) {
let seed = 0;
for (let i = 0; i < string.length; ++i) {
seed ^= string.charCodeAt(i) << i % 4 * 8;
}
return toUint32(seed);
}
function createNumberGenerator(seed) {
return new Uint32Array([
Math.imul(seed, 0x85ebca6b),
Math.imul(seed, 0xc2b2ae35),
]);
}
function generate(rng) {
let s0 = rng[0];
let s1 = rng[1] ^ s0;
rng[0] = (s0 << 26 | s0 >> 8) ^ s1 ^ s1 << 9;
rng[1] = s1 << 13 | s1 >> 19;
return toUint32(Math.imul(s0, 0x9e3779bb));
}
function generateBoolean(rng, probability) {
return generate(rng) < toUint32(probability * 0xffffffff);
}
function generateFloat(rng) {
return generate(rng) / 0xffffffff;
}
function generateNumber(rng, min, max) {
return min + generate(rng) % (max - min + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment