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
Release: 2024-11-04 17:35:02
Original
587 people have browsed it

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;
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template