Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active July 22, 2023 00:31
Show Gist options
  • Save steveruizok/09a1d3ff88175b077f9affbee1d4ce73 to your computer and use it in GitHub Desktop.
Save steveruizok/09a1d3ff88175b077f9affbee1d4ce73 to your computer and use it in GitHub Desktop.
Seeded random number generator in TypeScript.
/**
* Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift).
* Adapted from [seedrandom](https://github.com/davidbau/seedrandom).
* @param seed {string} The seed for random numbers.
*/
function rng(seed = '') {
let x = 0
let y = 0
let z = 0
let w = 0
function next() {
const t = x ^ (x << 11)
x = y
y = z
z = w
w ^= ((w >>> 19) ^ t ^ (t >>> 8)) >>> 0
return w / 0x100000000
}
for (var k = 0; k < seed.length + 64; k++) {
x ^= seed.charCodeAt(k) | 0
next()
}
return next
}
@steveruizok
Copy link
Author

This random number generator is "seeded". This means that the random numbers it generates will be the same for identical seeds, allowing randomization to be consistent between sessions. In my use case, shapes on a canvas need to be slightly wonky, however the shape's wonkiness needs to be consistent for that shape.

const getRandom = rng("someId")
getRandom() // always -0.1967178131453693
getRandom() // always 0.2110769241116941

In the above example, the function returned by rng("someId") will always produce -0.1967178131453693 when called the first time, 0.2110769241116941 when called the second time, and so on. You can try it yourself: you'll get the same results.

const getRandomA = rng("someId")
const getRandomB = rng("someId")
getRandomA() === getRandomB() // true (-0.1967178131453693)
getRandomA() === getRandomB() // true (0.2110769241116941)

A different seed will produce different results.

const getRandom = rng("someOtherId")
getRandom() // always 0.3126243716105819
getRandom() // always 0.18115195375867188

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment