// Seeded PRNG for the draw. With a seed the draw is reproducible (tests); without one the seed comes from // crypto.getRandomValues, so the result is unpredictable. /** cyrb128: hashes a string into four 32-bit seeds. */ function cyrb128(str: string): [number, number, number, number] { let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762; for (let i = 0; i < str.length; i++) { const k = str.charCodeAt(i); h1 = h2 ^ Math.imul(h1 ^ k, 597399067); h2 = h3 ^ Math.imul(h2 ^ k, 2869860233); h3 = h4 ^ Math.imul(h3 ^ k, 951274213); h4 = h1 ^ Math.imul(h4 ^ k, 2716044179); } h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067); h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233); h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213); h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179); h1 ^= h2 ^ h3 ^ h4; h2 ^= h1; h3 ^= h1; h4 ^= h1; return [h1 >>> 0, h2 >>> 0, h3 >>> 0, h4 >>> 0]; } /** sfc32 generator: returns floats in [0, 1). */ function sfc32(a: number, b: number, c: number, d: number): () => number { return () => { a |= 0; b |= 0; c |= 0; d |= 0; const 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) / 4294967296; }; } export type Rng = () => number; export function randomSeed(): string { const b = new Uint32Array(4); crypto.getRandomValues(b); return Array.from(b, (n) => n.toString(36)).join(''); } export function makeRng(seed: string): Rng { const rng = sfc32(...cyrb128(seed)); for (let i = 0; i < 15; i++) rng(); // warm up return rng; } export const randInt = (rng: Rng, n: number) => Math.floor(rng() * n); export function shuffle(rng: Rng, a: T[]): T[] { for (let i = a.length - 1; i > 0; i--) { const j = randInt(rng, i + 1); [a[i], a[j]] = [a[j], a[i]]; } return a; }