Skip to content

Instantly share code, notes, and snippets.

@MrBananaLord
Created January 18, 2023 08:55
Show Gist options
  • Save MrBananaLord/3d65e9c534149410f05075a288e2a55c to your computer and use it in GitHub Desktop.
Save MrBananaLord/3d65e9c534149410f05075a288e2a55c to your computer and use it in GitHub Desktop.
class Randomizer {
constructor(seed = "default") {
this.seed = seed;
this.seedHash = this.#cyrb128(seed);
this.rand = this.#sfc32(
this.seedHash[0],
this.seedHash[1],
this.seedHash[2],
this.seedHash[3]
);
}
shuffle(array) {
return array
.map(a => [this.rand(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
}
// sample(array) {
// return array[Math.floor((this.rand() * array.length))];
// }
// https://stackoverflow.com/a/47593316/6243352
#cyrb128(str) {
let h1 = 1779033703,
h2 = 3144134277,
h3 = 1013904242,
h4 = 2773480762;
for (let i = 0, k; i < str.length; i++) {
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);
return [(h1 ^ h2 ^ h3 ^ h4) >>> 0, (h2 ^ h1) >>> 0, (h3 ^ h1) >>> 0, (h4 ^ h1) >>> 0];
}
// https://stackoverflow.com/a/47593316/6243352
#sfc32(a, b, c, d) {
return function() {
a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
let t = (a + b) | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
d = d + 1 | 0;
t = t + d | 0;
c = c + t | 0;
return (t >>> 0) / 4294967296;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment