move random functions to rng class, fix some imports
This commit is contained in:
parent
07c08019f5
commit
432e1b6668
16 changed files with 71 additions and 80 deletions
|
|
@ -12,13 +12,30 @@ export class Rng {
|
|||
this.rand_low = seed ^ 0x49616E42
|
||||
}
|
||||
|
||||
random (min: number, max: number) {
|
||||
random (min: number, max: number): number {
|
||||
this.rand_high = ((this.rand_high << 16) + (this.rand_high >> 16) + this.rand_low) & 0xffffffff;
|
||||
this.rand_low = (this.rand_low + this.rand_high) & 0xffffffff;
|
||||
var n = (this.rand_high >>> 0) / 0xffffffff;
|
||||
return (min + n * (max-min+1))|0;
|
||||
}
|
||||
|
||||
// get one random item from the given array
|
||||
choice<T> (array: Array<T>): T {
|
||||
return array[this.random(0, array.length - 1)]
|
||||
}
|
||||
|
||||
// return a shuffled (shallow) copy of the given array
|
||||
shuffle<T> (array: Array<T>): Array<T> {
|
||||
const arr = array.slice()
|
||||
for (let i = 0; i <= arr.length - 2; i++) {
|
||||
const j = this.random(i, arr.length -1)
|
||||
const tmp = arr[i]
|
||||
arr[i] = arr[j]
|
||||
arr[j] = tmp
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
static serialize (rng: Rng): RngSerialized {
|
||||
return {
|
||||
rand_high: rng.rand_high,
|
||||
|
|
|
|||
|
|
@ -27,35 +27,6 @@ export const logger = (...pre: Array<any>) => {
|
|||
// get a unique id
|
||||
export const uniqId = () => Date.now().toString(36) + Math.random().toString(36).substring(2)
|
||||
|
||||
// get a random int between min and max (inclusive)
|
||||
export const randomInt = (
|
||||
rng: Rng,
|
||||
min: number,
|
||||
max: number,
|
||||
) => rng.random(min, max)
|
||||
|
||||
// get one random item from the given array
|
||||
export const choice = (
|
||||
rng: Rng,
|
||||
array: Array<any>
|
||||
) => array[randomInt(rng, 0, array.length - 1)]
|
||||
|
||||
// return a shuffled (shallow) copy of the given array
|
||||
export const shuffle = (
|
||||
rng: Rng,
|
||||
array: Array<any>
|
||||
) => {
|
||||
const arr = array.slice()
|
||||
for (let i = 0; i <= arr.length - 2; i++)
|
||||
{
|
||||
const j = randomInt(rng, i, arr.length -1);
|
||||
const tmp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = tmp;
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
function encodeShape(data: any): number {
|
||||
if (typeof data === 'number') {
|
||||
return data
|
||||
|
|
@ -196,9 +167,6 @@ const hash = (str: string): number => {
|
|||
export default {
|
||||
hash,
|
||||
uniqId,
|
||||
randomInt,
|
||||
choice,
|
||||
shuffle,
|
||||
|
||||
encodeShape,
|
||||
decodeShape,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue