Last active
July 9, 2020 11:49
-
-
Save tripzilch/7d31ad524a921324d709224227e0ad61 to your computer and use it in GitHub Desktop.
Seedable Xorshift128 PRNG
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
// RNG = Math.random | |
RNG = xorshift128 | |
function nonsense() { | |
// if all you need | |
// is a random seed | |
// of type string | |
// then this thing | |
// does the deed, hey | |
xorshift128_seed(Date.now() + ''); | |
const sample = (a) => a[Math.floor(RNG() * a.length)]; | |
const tok = x => () => sample(x.split(' ')); | |
const title = s => s.substring(0, 1).toUpperCase() + s.substring(1); | |
const vow = tok('a aa e ee i o oo au eu'); | |
const con1 = tok('b d f k l n p r z'); | |
const con2 = tok('k l r s t'); | |
const syl = () => con1() + vow() + sample([con2(), '']); | |
const word = () => [...$G.loop(1 + irand(3), syl)].join(''); | |
return title([...$G.loop(2 + irand(2), word)].join(' ')); | |
} | |
// TODO: test against ALEA generator | |
const xs_state = Uint32Array.of(0xC9A5, 0x5996, 0x5696, 0x9A33); // must not be all zero | |
function xorshift128() { | |
let s, t = xs_state[3]; | |
xs_state[3] = xs_state[2]; | |
xs_state[2] = xs_state[1]; | |
xs_state[1] = s = xs_state[0]; | |
t ^= t << 11; | |
t ^= t >>> 8; | |
xs_state[0] = t ^ s ^ (s >>> 19); | |
return xs_state[0] / 0x100000000; | |
} | |
function xorshift128_seed(seed_str) { | |
const FNV_prime = 16777619; | |
xs_state.fill(2166136261); | |
for (let i = 0; i < seed_str.length; i++) { | |
const j = i & 3; | |
xs_state[j] ^= seed_str.charCodeAt(i); | |
xs_state[j] *= FNV_prime; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment