refactors
This commit is contained in:
@@ -3,16 +3,16 @@
|
||||
* using the xorshift32 method.
|
||||
*/
|
||||
export class Xorshift32 {
|
||||
/* @type {number} */
|
||||
initialSeed;
|
||||
|
||||
/**
|
||||
* State holds a single uint32.
|
||||
* It's useful for staying within modulo 2**32.
|
||||
*
|
||||
* @type {Uint32Array}
|
||||
*/
|
||||
state;
|
||||
#state;
|
||||
get state() {
|
||||
return this.#state;
|
||||
}
|
||||
|
||||
/** @param {number} seed */
|
||||
constructor(seed) {
|
||||
@@ -21,41 +21,44 @@ export class Xorshift32 {
|
||||
seed = Math.floor(Math.random() * (maxInt32 - 1)) + 1;
|
||||
}
|
||||
seed = seed | 0;
|
||||
this.state = Uint32Array.of(seed);
|
||||
this.#state = Uint32Array.of(seed);
|
||||
}
|
||||
|
||||
/** @protected Shuffle the internal state. */
|
||||
shuffle() {
|
||||
this.state[0] ^= this.state[0] << 13;
|
||||
this.state[0] ^= this.state[0] >>> 17;
|
||||
this.state[0] ^= this.state[0] << 5;
|
||||
this.#state[0] ^= this.#state[0] << 13;
|
||||
this.#state[0] ^= this.#state[0] >>> 17;
|
||||
this.#state[0] ^= this.#state[0] << 5;
|
||||
|
||||
// We could also do something like this:
|
||||
// x ^= x << 13;
|
||||
// x ^= x >> 17;
|
||||
// x ^= x >>> 17;
|
||||
// x ^= x << 5;
|
||||
// return x;
|
||||
// But we'd have to xor the x with 2^32 after every op,
|
||||
// we get that "for free" by using the uint32array
|
||||
// And even though bitwise operations coerce numbers
|
||||
// into int32 (except >>> which converts into uint32).
|
||||
// But using Uint32Array ensures the number stays
|
||||
// uint32 all the way through, thus avoiding the pitfalls
|
||||
// of potentially dipping into negative number territory
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random number and shuffle the internal state.
|
||||
* @returns {number} a pseudo-random positive integer.
|
||||
*/
|
||||
get() {
|
||||
next() {
|
||||
this.shuffle();
|
||||
return this.state[0];
|
||||
return this.#state[0];
|
||||
}
|
||||
|
||||
/** @param {number} x @returns {number} a positive integer lower than x */
|
||||
lowerThan(x) {
|
||||
return this.get() % x;
|
||||
return this.next() % x;
|
||||
}
|
||||
|
||||
/** @param {number} x @returns {number} a positive integer lower than or equal to x */
|
||||
lowerThanOrEqual(x) {
|
||||
return this.get() % (x + 1);
|
||||
return this.next() % (x + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user