Created
October 25, 2023 14:25
-
-
Save camilacanhete/8eaa67c11ef51117b6bc31a7b167af8e to your computer and use it in GitHub Desktop.
Pseudo random with seed
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
/** | |
* Generates a random number using a seed | |
* @author csantos | |
*/ | |
export class PseudoRandom { | |
private state: number; | |
/** | |
* Creates a new Random instance with the specified seed | |
* @param seed - the seed for initializing the random number generator | |
*/ | |
constructor(seed: number) { | |
this.state = seed; | |
} | |
/** | |
* Generates the next pseudo-random float value in the range [0, 1) | |
* @returns a pseudo-random float value | |
*/ | |
public rand(): number { | |
this.state = (this.state * 9301 + 49297) % 233280; | |
return this.state / 233280; | |
} | |
/** | |
* Generates a pseudo-random integer within the specified range [min, max] | |
* @param min - the minimum value of the range | |
* @param max - the maximum value of the range | |
* @returns a pseudo-random integer | |
*/ | |
public randRange(min: number, max: number): number { | |
const range: number = max - min + 1; | |
return Math.floor(min + this.rand() * range); | |
} | |
/** | |
* Generates a sequence of 'x' pseudo-random integers within the specified range [min, max] | |
* @param x - the number of random integers to generate | |
* @param min - the minimum value of the range | |
* @param max - the maximum value of the range | |
* @returns an array of pseudo-random integers | |
*/ | |
public randSequence(x: number, min: number, max: number): Array<number> { | |
const sequence: Array<number> = new Array(); | |
for (let i = 0; i < x; i++) { | |
sequence.push(this.randRange(min, max)); | |
} | |
return sequence; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment