Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save alesmenzel/6164543b3d018df7bcaf6c5f9e6a841e to your computer and use it in GitHub Desktop.

Select an option

Save alesmenzel/6164543b3d018df7bcaf6c5f9e6a841e to your computer and use it in GitHub Desktop.
Select random element from array by probability
const arr = ['A', 'B', 'C'];
// Probability map
const weight = {
A: 0.5,
B: 0.3,
C: 0.2
};
const find = input =>
arr.find((el, i) => {
const sum = arr.slice(0, i + 1).reduce((acc, el) => {
return acc + weight[el];
}, 0);
if (input < sum) {
return true;
}
return false;
});
console.log(find(0.45)); // A <0, 0.5)
console.log(find(0.6)); // B <0.5, 0.8)
console.log(find(0.85)); // C <0.8, 1) - 1 is exclusive, same as Math.random()
console.log(find(Math.random())); // Random
@TheTridentGuy
Copy link

TheTridentGuy commented Jul 23, 2022

This seems to work:

var li = {'A': 0, 'B':0, 'C':0}
for(i=0; i<1000; i++){
    li[find(Math.random())] += 1
}

-> {A: 518, B: 287, C: 195}

Thx for the code, just what i needed!

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