Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active June 5, 2024 07:10
Show Gist options
  • Save lewdev/f1889c5d0429bb0e7457f8ce1b2fc89d to your computer and use it in GitHub Desktop.
Save lewdev/f1889c5d0429bb0e7457f8ce1b2fc89d to your computer and use it in GitHub Desktop.
🌱 Random Seed Methods

🌱 Random Seed Methods

I wanted to see what's out there and here's what I found.

I think this is decent set to study, but I'm mainly interested in the smallest implementation and not worried about if it's computationally random.

@KilledByAPixel (source)

rand = max => Math.sin(++seed)**2 * 1e9 % max

LCG by Jonathan Pugh (@jdspugh) (source)

"longer but faster"

LCG = s => () => (s = Math.imul(741103597, s) >>> 0) / 2 ** 32

prng by anechunaev (source)

const prng = s => (typeof s!=='undefined'&&((l=s%2147483647)<=0&&(l+=2147483646)),((l=l*16807%2147483647)-1)/2147483646);
console.log(prng(seed));		// 0.000023478642127922403
console.log(prng());		// 0.3946133641475936
console.log(prng());		// 0.26681596624368425

Just call it again with seed to start new sequence.

bijou seedRandom (source)

req describes the required argument and what data type it must be. (see source for that)

export let seedRandom = (seed = req("number", "seed")) => {
  var t = (seed += 0x6d2b79f5);
  t = Math.imul(t ^ (t >>> 15), t | 1);
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};

davidbau seedrandom (source)

<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js">
</script>

This has multiple features including using a string as a seed but has a lot more code. See source for example usage.

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