Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 32x 32x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 2x | import prand from 'pure-rand'
export default class NumberGenerator {
private generator: prand.RandomGenerator
public seed: number
constructor(seed?: number) {
this.seed = seed ?? Date.now() ^ (Math.random() * 0x100000000)
this.generator = prand.xoroshiro128plus(this.seed)
}
/**
* Returns a uniformly distributed random integer between min and max
*/
public uniformInt(min: number, max: number): number {
const [value, rng] = prand.uniformIntDistribution(min, max)(this.generator)
this.generator = rng
return value
}
/*
* Returns a uniformly distributed random float between min and max
*/
public uniformFloat(min: number, max: number) {
const [value, rng] = prand.uniformIntDistribution(min * 1000, max * 1000)(this.generator)
this.generator = rng
return value / 1000
}
/**
* Returns a normally distributed random number with mean mu and standard deviation sigma.
*/
public normalFloat(mu: number, sigma: number): number {
let u = 0, v = 0
while(u === 0) u = 1 - this.uniformFloat(0, 1)
while(v === 0) v = this.uniformFloat(0, 1)
return sigma * Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v ) + mu
}
/**
* Picks a single random element from the array.
* Returns undefined if the array is empty.
*/
public pickRandom<T>(array: T[]): T {
if (array.length === 0) {
return undefined
}
return array[this.uniformInt(0, array.length - 1)]
}
/**
* Picks a random subset of the array without replacement.
* Returns an empty array if the array is empty.
*/
public pickRandomArray<T>(array: T[], size: number): T[] {
Iif (array.length === 0) {
return []
}
const result: T[] = []
const copy = array.slice()
const limit = Math.min(size, copy.length)
for (let i = 0; i < limit; i++) {
const index = this.uniformInt(0, copy.length - 1)
result.push(copy[index])
copy.splice(index, 1)
}
return result
}
}
|