// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini import crypto from 'node:crypto'; export class Rng { private a: number; private b: number; private c: number; private d: number; constructor(readonly seed: string) { const h = crypto.createHash('sha256').update(seed, 'utf8').digest(); this.a = h.readUInt32LE(0); this.b = h.readUInt32LE(4); this.c = h.readUInt32LE(8); this.d = h.readUInt32LE(12); for (let i = 0; i < 12; i++) this.nextUint32(); } fork(label: string): Rng { return new Rng(`${this.seed}/${label}`); } nextUint32(): number { const t = (((this.a + this.b) >>> 0) + this.d) >>> 0; this.d = (this.d + 1) >>> 0; this.a = this.b ^ (this.b >>> 9); this.b = (this.c + (this.c << 3)) >>> 0; this.c = ((this.c << 21) | (this.c >>> 11)) >>> 0; this.c = (this.c + t) >>> 0; return t; } next(): number { return this.nextUint32() / 4294967296; } int(min: number, max: number): number { return min + Math.floor(this.next() * (max - min + 1)); } bool(pTrue = 0.5): boolean { return this.next() < pTrue; } pick(items: readonly T[]): T { if (items.length === 0) throw new Error('pick from an empty array'); return items[this.int(0, items.length - 1)]; } weighted(items: ReadonlyArray): T { const total = items.reduce((s, [, w]) => s + w, 0); let r = this.next() * total; for (const [item, w] of items) { r -= w; if (r < 0) return item; } return items[items.length - 1][0]; } shuffle(items: readonly T[]): T[] { const a = [...items]; for (let i = a.length - 1; i > 0; i--) { const j = this.int(0, i); [a[i], a[j]] = [a[j], a[i]]; } return a; } sample(items: readonly T[], n: number): T[] { return this.shuffle(items).slice(0, Math.min(n, items.length)); } string(length: number, alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'): string { const chars = [...alphabet]; let s = ''; for (let i = 0; i < length; i++) s += chars[this.int(0, chars.length - 1)]; return s; } } export function testSeed(runSeedValue: string, titlePath: readonly string[]): string { return `${runSeedValue}::${titlePath.join(' > ')}`; }