Home  >  Article  >  Web Front-end  >  How can I create a repeatable sequence of random numbers in JavaScript?

How can I create a repeatable sequence of random numbers in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 06:50:01855browse

How can I create a repeatable sequence of random numbers in JavaScript?

Providing a Custom Seed for JavaScript Random Number Generator

The default JavaScript Math.random() function generates random values within the range [0, 1], but it does not allow you to set a custom seed. Consequently, the generated sequence of random numbers is non-repeatable.

To create a JavaScript random number generator with a customizable seed, we can explore multiple options:

Math.random() Helper Functions:

If you don't need custom seeding, you can utilize Math.random() with helper functions to create a repeatable range of values (e.g., randRange(start, end)).

Pseudorandom Number Generators (PRNGs):

For more control over the randomness, consider using PRNGs like the Mersenne Twister. However, its implementation is complex. An alternative is a Linear Congruential Generator (LCG), which is easier to implement and provides decent randomness.

LCG Implementation (Short Seedable RNG):

Below is an example implementation of a short seedable RNG using 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;
};

RNG.prototype.nextFloat = function() {
  // returns in range [0,1]
  return this.nextInt() / (this.m - 1);
};

RNG.prototype.nextRange = function(start, end) {
  // returns in range [start, end): including start, excluding end
  // can't modulu nextInt because of weak randomness in lower bits
  var rangeSize = end - start;
  var randomUnder1 = this.nextInt() / this.m;
  return start + Math.floor(randomUnder1 * rangeSize);
};

RNG.prototype.choice = function(array) {
  return array[this.nextRange(0, array.length)];
};</code>

To use the RNG:

<code class="js">var rng = new RNG(20);
for (var i = 0; i < 10; i++)
  console.log(rng.nextRange(10, 50));

var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
for (var i = 0; i < 10; i++)
  console.log(rng.choice(digits));</code>

The above is the detailed content of How can I create a repeatable sequence of random numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn