Home >Web Front-end >JS Tutorial >How to Create a Seedable Random Number Generator in JavaScript?

How to Create a Seedable Random Number Generator in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 17:35:02574browse

How to Create a Seedable Random Number Generator in JavaScript?

Seedable JavaScript Random Number Generator

The JavaScript Math.random() function generates random values between 0 and 1 based on the current time, similar to Java's random number generator. However, it lacks the ability to specify a seed value to control the sequence of generated numbers.

Creating a Custom Random Number Generator with Seed Support

To create a random number generator with seed support, consider the following options:

Implementing a Linear Congruential Generator (LCG)

LCGs are relatively simple to implement and provide decent randomness qualities. You can utilize the following constants:

m = 0x80000000; // 2**31
a = 1103515245;
c = 12345;

Here's an example implementation in JavaScript:

<code class="javascript">function RNG(seed) {
  this.m = 0x80000000;
  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>

You can extend this RNG class to provide additional methods like nextFloat, nextRange, and choice based on the LCG core.

Utilizing Libraries for Short Seedable RNGs

Libraries such as [js-random](https://www.npmjs.com/package/js-random) provide short, seedable RNGs with options for different algorithms.

Example Implementation

Here's a simple example using an LCG-based RNG:

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

The above is the detailed content of How to Create a Seedable Random Number Generator 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