Created
May 2, 2023 10:55
-
-
Save developersharif/948694db21e1685365152d5c9d8ae53b to your computer and use it in GitHub Desktop.
The code provides a simple implementation of the Linear Congruential Generator (LCG) algorithm in JavaScript. LCG is a type of pseudo-random number generator that produces a sequence of numbers that appear to be random but are actually determined by a mathematical formula. The algorithm takes a seed value as input and generates a sequence of pse…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LCG { | |
constructor() { | |
this.seed = Date.now(); | |
this.a = 1664525; | |
this.c = 1013904223; | |
this.m = Math.pow(2, 32); | |
} | |
nextInt() { | |
this.seed = (this.a * this.seed + this.c) % this.m; | |
return this.seed; | |
} | |
randomInt(min, max) { | |
const range = max - min + 1; | |
return Math.floor(this.nextInt() / (this.m / range)) + min; | |
} | |
randomFloat(min, max) { | |
return this.nextInt() / this.m * (max - min) + min; | |
} | |
} | |
// Example usage: | |
const generator = new LCG(); | |
console.log(generator.randomInt(1, 10)); // Prints a random integer between 1 and 10 | |
console.log(generator.randomFloat(0, 1)); // Prints a random float between 0 and 1 | |
console.log(generator.randomInt(1, 10)); // Prints a new random integer between 1 and 10 | |
console.log(generator.randomFloat(0, 1)); // Prints a new random float between 0 and 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment