Skip to content

Instantly share code, notes, and snippets.

@AryanJ-NYC
Created August 30, 2016 23:07
Show Gist options
  • Save AryanJ-NYC/a5bf03dd5a4ecd08832a6aa366557146 to your computer and use it in GitHub Desktop.
Save AryanJ-NYC/a5bf03dd5a4ecd08832a6aa366557146 to your computer and use it in GitHub Desktop.
function selector(weights) {
let maxRandom = [];
let curr = 0;
for (let i = 0; i < weights.length; ++i) {
let currentWeight = weights[i];
curr += currentWeight;
maxRandom.push(curr);
}
let randomNum = Math.random();
for (let i = 0; i < maxRandom.length; ++i) {
if (randomNum <= maxRandom[i]) {
return i;
}
}
}
let weights = [0.3, 0.2, 0.5];
let counts = [0, 0, 0];
const NUM_TRIALS = 5000;
for (let i = 0; i < 5000; ++i) {
++counts[selector(weights)];
}
for (let i = 0; i < counts.length; ++i) {
console.log(`Index ${i}'s real probability is ${counts[i]/NUM_TRIALS}`);
console.log(`Index ${i}'s expected probability is ${weights[i]}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment