Last active
September 7, 2020 08:37
-
-
Save rauschma/9d10b7e1c81ba6f19998e070c7849174 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
/** Get a random integer 0 <= i < max */ | |
function getRandomInteger(max) { | |
return Math.floor(Math.random() * max); | |
} | |
function getWeightedChoice(choices, weights) { | |
const sumOfWeights = weights.reduce((acc, x) => acc + x, 0); | |
let randomInt = getRandomInteger(sumOfWeights) + 1; | |
for (const [index, weight] of weights.entries()) { | |
randomInt = randomInt - weight; | |
if (randomInt <= 0) { | |
return choices[index]; | |
} | |
} | |
throw new Error('This shouldn’t happen'); | |
} | |
console.log(getWeightedChoice(['a', 'b'], [50, 50])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Different approach (not necessarily better):