Creating a Seedable JavaScript Random Number Generator
The Math.random() function in JavaScript provides a random number between 0 and 1, automatically initialized based on the current time. However, there is a need for a random number generator that allows for user-defined seed values to produce repeatable sequences of pseudo-random numbers.
Solution:
Implementing a seedable random number generator involves choosing a suitable pseudorandom number generator (PRNG) algorithm that supports seeding. One popular option is the Mersenne Twister algorithm, known for its excellent randomness and long period.
However, implementing Mersenne Twister can be complex. For beginners, an alternative like a linear congruential generator (LCG) is recommended. LCGs are simple to implement and provide decent randomness, although they are not as strong as Mersenne Twister.
LCG Implementation (RNG Class)
The following snippet demonstrates an LCG implementation in JavaScript using GCC's constants:
<code class="javascript">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>
Usage:
Create an instance of the RNG class with a desired seed value:
<code class="javascript">var rng = new RNG(20);</code>
Access random integers:
<code class="javascript">for (var i = 0; i < 10; i++) console.log(rng.nextInt());</code>
Generate random floating-point numbers (0 to 1):
<code class="javascript">for (var i = 0; i < 10; i++) console.log(rng.nextFloat());</code>
Generate random values within a specified range:
<code class="javascript">for (var i = 0; i < 10; i++) console.log(rng.nextRange(10, 50)); // Random integers between 10 (inclusive) and 50 (exclusive)</code>
Select random elements from an array:
<code class="javascript">var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; for (var i = 0; i < 10; i++) console.log(rng.choice(digits)); // Random digits from the array</code>
The above is the detailed content of How to Create a Consistent Random Number Generator in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!