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.
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).
Note: every time
randomInt()
method is called, it is necessary to update seed value.
xxxxxxxxxx
1
class CustomRandom {
2
private A: number = 1103515245; // multiplier
3
private C: number = 12345; // incrementer
4
private M: number = 2147483647; // modulus == max integer value
5
6
public constructor(private seed: number = Date.now()) { /* Nothing here ... */ }
7
8
public nextInt = (): number => {
9
this.seed = (this.seed * this.A + this.C) % this.M;
10
return this.seed;
11
};
12
13
public nextDouble = (): number => {
14
const value = this.nextInt();
15
return value / this.M;
16
};
17
}
18
19
20
// Usage example 1:
21
22
const random1 = new CustomRandom(3819201); // 3819201 is example initial seed
23
24
console.log(random1.nextInt()); // 348328093
25
console.log(random1.nextInt()); // 121065958
26
console.log(random1.nextInt()); // 790325445
27
28
29
// Usage example 2 (values should be different always):
30
31
const random2 = new CustomRandom();
32
33
console.log(random2.nextInt()); // 922892575
34
console.log(random2.nextInt()); // 1117277734
35
console.log(random2.nextInt()); // 2084933141
36
37
console.log(random2.nextDouble()); // 0.6316955399847103
38
console.log(random2.nextDouble()); // 0.5716405932659472
39
console.log(random2.nextDouble()); // 0.3298228519641901