Let's say you have the arrays
String[] possibleOutcomes = new String[] { "A", "B", "C", "D" }
and
int[] possibleOutcomeProbabilities = new int[] { 30, 14, 31, 25 }
You can use the following strategy whenever you are required to output one of the outcomes:
- Find the sum of all elements in
possibleOutcomeProbabilities
. Lets call this sum totalProbability
.
- Generate a random number between
1
and totalProbability
. Lets call this randomly generated number outcomeBucket
.
- Iterate over
possibleOutcomeProbabilities
to determine which outcome outcomeBucket
corresponds to. You then pick the corresponding outcome from possibleOutcomes
.
This strategy will certainly not give you first 30% outcomes as A, next 14% as B, etc. However, as probability works, over a sufficiently large number of outcomes, this strategy will ensure that your possible outcomes are distributed as per their expected probabilities. This strategy gives you the advantage that outcome probabilities are not required to add up to 100%. You can even specify relative probabilities, such as, 1:2:3:4, etc.
If you are really worried about the fastest possible implementation for the strategy, you can tweak it as follows:
a. Calculate totalProbability
only once, or when the probablities are changed.
b. Before calculating totalProbability
, see if the elements in possibleOutcomeProbabilities
have any common divisors and eliminate those. This will give you a smaller probability space to traverse each time.