Last active
July 25, 2025 05:22
-
-
Save alesmenzel/6164543b3d018df7bcaf6c5f9e6a841e to your computer and use it in GitHub Desktop.
Select random element from array by probability
This file contains hidden or 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
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems to work:
Thx for the code, just what i needed!