Danny
Danny

Reputation: 1003

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

Upvotes: 6

Views: 3448

Answers (2)

Jakob Povsic
Jakob Povsic

Reputation: 74

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.

Upvotes: 3

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

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.

Upvotes: 7

Related Questions