Hong-Phuc Bui
2025-01-16 2889de7f0c2d587a17fbd322af57c29e84238620
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
/**
* implement some useful random-function
*/
 
 
 
/**
 * generates a random integer in [{@param inclusiveMin}; {@param exclusiveMax}).
 *
 * @param inclusiveMin {number}
 * @param exclusiveMax {number}
 *
 * @return {number} a random integer in [{@param inclusiveMin}; {@param exclusiveMax}).
 *
 */
export function uniform(inclusiveMin= 0, exclusiveMax) {
    let a = inclusiveMin,
        b = exclusiveMax;
    if (arguments.length === 1) { // only the first is set => there is no left bound
        a = 0;
        b = inclusiveMin;
    }
    if ( (b <= a) || (b-a) >= Number.MAX_VALUE ) {
        throw Error(`bad range [${a}, ${b})`)
    }
    return a + (Math.floor( (b-a)*Math.random() ));
}
 
 
/**
 * generates a random discrete distribution of a given probability of distribution
 * For example: given a probability of `[0.1, 0.3, 0.6]`, then the random generate number ist
 * one of 0 (with probability of 1%) , 1 (30%) and 2(60%).
 *
 * @param distribution {Array} an array of number, sum of its element must be at most 1
 * @return {number} an integer between 0 (include) and {@param distribution.length} (exclude)
 *
 * */
export function discrete(distribution) {
    let sum = distribution.reduce( (acc,current) => acc + current);
    let dist = undefined;
    if(sum > 1) {
        throw Error(`bad distribution [${distribution}]`);
    } else if (sum < 1) {
        dist = [...distribution, 1 - sum];
    } else {
        dist = [...distribution];
    }
    let r = Math.random();
    let i = 0;
    let acc = dist[0];
    while(r >=acc ) {
        ++i;
        acc += dist[i];
    }
    return i;
}