I have a list of items. Each of these items has its own probability.
Can anyone suggest an algorithm to pick an item based on its probability?
I have a list of items. Each of these items has its own probability.
Can anyone suggest an algorithm to pick an item based on its probability?
pretend that we have the following list
Lets pretend that all the probabilities are integers, and assign each item a "range" that calculated as follows.
The new numbers are as follows
Now pick a random number from 0 to 100. Lets say that you pick 32. 32 falls in Item B's range.
mj
Algorithm described in Ushman's, Brent's and @kaushaya's answers are implemented in Apache commons-math library.
Take a look at EnumeratedDistribution class (groovy code follows):
Note that sum of probabilities doesn't need to be equal to 1 or 100 - it will be normalized automatically.
Sample code:
If you don't mind adding a third party dependency in your code you can use the MockNeat.probabilities() method.
For example:
Disclaimer: I am the author of the library, so I might be biased when I am recommending it.