Okay, imagine I'm creating a Pokemon game in JavaScript. I have an object like this...
pokemon = {
"pikachu": {hp: 100, probability: 0.1},
"squirtle": {hp: 90, probability: 0.2}
};
I basically need a function to select a pokemon in the object at random, but also based on the probability. So, in this case, the functions more likely to select a "squirtle" as it's probability is higher than "pikachu".
I would loop through the pokemon array and add up all of the probabilities. Call this total
Then generate a value between 0 and total
. Call this randVal
Then loop through, adding up the probabilities again. Call this secondTotal
The first pokemon whose probability would push secondTotal
above randVal
is your selected pokemon.
function pickAWinningItem(data) {
var winner = Math.random();
var threshold = 0;
for (let i = 0; i < data.length; i++) {
threshold += parseFloat(data[i].prob);
if (threshold > winner) {
return data[i]
}
}
}
The sum of all probabilities must be equal to 1. With this function you stack the probabilities on top of each other and return the item, that the random number is the range of its probability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With