Get a random element for an array based on different probabilities?

Well, imagine I'm creating a Pokemon game in JavaScript. I have such an object ...

pokemon = { "pikachu": {hp: 100, probability: 0.1}, "squirtle": {hp: 90, probability: 0.2} }; 

I basically need a function to select PokΓ©mon in an object at random, but also based on probability. Thus, in this case, the functions are more likely to select "squirtle", since the probability is higher than "pikachu".

+6
source share
2 answers

I would go through the pokemon array and summarize all the probabilities. Call it total

Then create a value from 0 to total . Call it randVal

Then scroll, adding probabilities again. Call it secondTotal
The first pokemon, the probability of which clicks secondTotal above randVal , is your chosen pokemon.

+6
source
 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 the probabilities should be 1. Using this function, you add probabilities on top of each other and return the element that a random number is the range of its probability.

+1
source

Source: https://habr.com/ru/post/944156/


All Articles