Created
August 30, 2016 23:07
-
-
Save AryanJ-NYC/a5bf03dd5a4ecd08832a6aa366557146 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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