Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active September 7, 2020 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/9d10b7e1c81ba6f19998e070c7849174 to your computer and use it in GitHub Desktop.
Save rauschma/9d10b7e1c81ba6f19998e070c7849174 to your computer and use it in GitHub Desktop.
/** 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]));
@bitifet
Copy link

bitifet commented Sep 7, 2020

Different approach (not necessarily better):

function getWeightedChoice(choices, weights) {
    return choices
        .map((c,i) => [c, Math.floor(Math.random() * weights[i])])
        .sort((a,b)=>b[1]-a[1])
        [0][0]
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment