EN
TypeScript - own random number generator (custom implementation)
3
points
In this article, we're going to have a look at how to write own random numbers generator that is based on LCG (Linear congruential generator) algorithm in TypeScript.
1. Introduction
In TypeScript, we can implement a custom random number generator by using LCG (Linear congruential generator) algorithm. LCG is one of the oldest and best-known pseudorandom number generator algorithm. We can adjust this implementation to work on int or long.
The linear congruential generator is defined by the recurrence formula:
Where:
Xn+1
- new seed,a
- multiplier,Xn
- current seed (comes from previous calculations),c
- incrementer,m
- modulus (max integer value).
2. Implementation
Note: every time
randomInt()
method is called, it is necessary to update seed value.
class CustomRandom {
private A: number = 1103515245; // multiplier
private C: number = 12345; // incrementer
private M: number = 2147483647; // modulus == max integer value
public constructor(private seed: number = Date.now()) { /* Nothing here ... */ }
public nextInt = (): number => {
this.seed = (this.seed * this.A + this.C) % this.M;
return this.seed;
};
public nextDouble = (): number => {
const value = this.nextInt();
return value / this.M;
};
}
// Usage example 1:
const random1 = new CustomRandom(3819201); // 3819201 is example initial seed
console.log(random1.nextInt()); // 348328093
console.log(random1.nextInt()); // 121065958
console.log(random1.nextInt()); // 790325445
// Usage example 2 (values should be different always):
const random2 = new CustomRandom();
console.log(random2.nextInt()); // 922892575
console.log(random2.nextInt()); // 1117277734
console.log(random2.nextInt()); // 2084933141
console.log(random2.nextDouble()); // 0.6316955399847103
console.log(random2.nextDouble()); // 0.5716405932659472
console.log(random2.nextDouble()); // 0.3298228519641901