Home >Web Front-end >JS Tutorial >How do I create a seedable random number generator in JavaScript?
Implementing a Seedable JavaScript Random Number Generator
It is a common requirement to generate a sequence of random numbers in JavaScript, but the built-in Math.random() function lacks the ability to set a specific seed. This can be problematic when we want to reproduce a particular sequence of numbers or create deterministic randomness.
Using a Custom Random Number Generator
To overcome this limitation, we can implement a custom random number generator that allows us to specify a seed value. Here's an example using a Linear Congruential Generator (LCG):
<code class="js">function RNG(seed) { this.m = 0x80000000; // 2**31 this.a = 1103515245; this.c = 12345; this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1)); } RNG.prototype.nextInt = function() { this.state = (this.a * this.state + this.c) % this.m; return this.state; }</code>
This LCG produces a sequence of integers between 0 and (2**31 - 1). Other types of random number generators, such as Mersenne Twister, provide stronger randomness guarantees but are more complex to implement.
Setting a Seed Value
To set a seed value, we can pass it as an argument to the RNG constructor:
<code class="js">var rng = new RNG(20);</code>
This will initialize the internal state of the generator with the specified seed, ensuring that it produces a repeatable sequence of numbers.
Using the Random Number Generator
The custom RNG provides the following methods:
For example, to generate a sequence of random numbers between 10 and 50:
<code class="js">for (var i = 0; i < 10; i++) console.log(rng.nextRange(10, 50));</code>
Additional Considerations
The above is the detailed content of How do I create a seedable random number generator in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!