Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random item for array based on different probabilities?

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".

like image 532
Danny Avatar asked May 02 '13 19:05

Danny


2 Answers

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.

like image 72
Jean-Bernard Pellerin Avatar answered Nov 08 '22 00:11

Jean-Bernard Pellerin


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.

like image 29
Jakob Povsic Avatar answered Nov 07 '22 23:11

Jakob Povsic