Load Distribution (rejection sampling)

JS
S
JavaScript

Rejection Sampling using JavaScript

1var versions = {a: 0.2, b: 0.3, c: 0.5};
2
3// Rejection sampling
4function weightedRand(spec) {
5  var i, j, table=[];
6  for (i in spec) {
7    for (j=0; j<spec[i]*10; j++) {
8      table.push(i);
9    }
10  }
11  return function() {
12    return table[Math.floor(Math.random() * table.length)];
13  }
14}
15
16// Output
17var random = weightedRand(versions);
18
19// Results
20var results = [];
21
22
23// Sampler
24const RUNS = 1;
25for (let index = 0; index < RUNS; index++) {
26   results.push(random());
27}
28
29// Statistics
30var stats = results.reduce(function (acc, curr) {
31  if (typeof acc[curr] == 'undefined') {
32    acc[curr] = 1;
33  } else {
34    acc[curr] += 1;
35  }
36
37  return acc;
38}, {});
39
40console.log(stats)
41
42// Pretty stats
43// var percentageA = (stats.a / RUNS) * 100;
44// var percentageB = (stats.b / RUNS) * 100;
45// var percentageC = (stats.c / RUNS) * 100;
46// console.log('A', percentageA, 'original:', versions.a);
47// console.log('B', percentageB, 'original:', versions.b);
48// console.log('C', percentageC, 'original:', versions.c);
49
50
51
52
53

Created on 8/30/2018