Seeded, pseudorandom number generator. The main export is
random which can be a drop in replacement for
Good for simple video games, terrain generation, texture generation, or times when you need to make use of a random number generator that can produce the same results over different runs (via the initial seed).
Note from author: I do not know enough about cryptography to speak about the suitability of this code for that application. Let's say it's not suitable. Please don't use this for encryption. Please find another solution when you need strong, unpredictable hashing.
npm install @trinkets/random
// or import * as random from '@trinkets/random'// Substitute for Math.random()console// For when you want integers, here 1 <= result <= 10 (i.e. min <= x <= max)console// Choose an element from a sequence.console// Choose a random set of elements from a list (can have repeats).console// Choose a random set of weighted elements from a list (can have repeats).console// Choose a random set of elements from a list, no repeats.console// What is the initial seed usedconsole// Reset the seed with a non-zero integer.console// Get the internal state as an object literal (`JSON.stringify`able).const restorePoint = state// Make some random numbers or do other things.// ...// Restore the state back to whenever you took it. Any random numbers generated// will be regenerated from the restorePoint.state// When you need to manage the state of a separate random number generator.const rng2 =// Same API.consoleconsole
This code originally started with an older version of the multiply-with-carry wikipedia article. The original code was:
m_w = /* choose some initializer, must not be zero */;m_z = /* choose some initializer, must not be zero */;uint
For the times I've needed to reproduce my number generation with a seed, this code has been good enough.
Some not-rigorous-tests on jsperf within my Chrome browser show this code to be about 20% faster than
Math.random. Some additional not-rigorous-monte-carlo-tests (millions of runs) show the distribution of
Math.random and this to have similar distributions of numbers.