Skip to content

Instantly share code, notes, and snippets.

@developersharif
Created May 2, 2023 10:55
Show Gist options
  • Save developersharif/948694db21e1685365152d5c9d8ae53b to your computer and use it in GitHub Desktop.
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…
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