How to randomly pick items with given probabilities for each

841 Views Asked by At

How can I randomly pick an item from a set of items if I want each item to have a different probability of being picked?

Example:
Suppose I have a set of strings: Apple, Banana, Orange
I want "Apple" to be picked 56.45% of the time, "Banana" 31.22% of the time, and "Orange" 12.33% of the time.
How can I do this? I don't want to round the percentage.

1

There are 1 best solutions below

1
On BEST ANSWER

Random number generators tend to return a value $x \in [0,1)$. (including 0, but excluding 1). In the case of pseudo random number generators, this is usually the decimal representation of a fraction with a very large denominator. What we need to do is therefore translate the given probabilities to a unit interval.

Here we have probabilities 0.5645, 0.3122, and 0.1233 that add up to unity. So what we can do is use the following algorithm:

if $x \in [0,0.5645)$ we have an apple

if $x \in [0.5645,0.8767)$ we have a banana

if $x \in [0.8767,1)$ we have an orange

Note that 0.8767=0.5645+0.3122 and 1 = 0.5645+0.3122+0.1233 and the length of each interval corresponds to the related probability. What you do here is creating a cumulative table of the probabilities. This can of course easily be generalised to more "fruits".

This same approach can be used to draw random numbers from a continous non-homogenous distribution, but the cumulative table becomes an integration of the distribution, which is only a little bit more complicated.

Functions in programming languages, like what Henry mentioned, essentially do just this.