For an AI I'm using random values to decide which action to perform next (only when there is nothing rule based to do). Some of the actions should be picked more often than others.
The idea is to define a group of probabilities and pick an action from the probs 2 twice as often then an action with 1, the action 4 with a five times higher probability.
action prob
0 1
1 2 (twice as often than 1)
2 2
3 2
4 5 (5 times morer often than 1)
Is there a wellknown algorithm for this behaviour or a more mathematical approach?
My test implementation is somewhat awkward. I would prefer to avoid the inner loop.
public static void main(String[] args) {
int[] counts = new int[5];
int[] props = { 1 ,2 ,2 ,2 ,5 };
int sum = 0;
for (int i = 0; i < props.length ; i++) {
sum += props[i];
}
for ( int i = 0 ; i < 100 ; i++ ) {
int rand = (int) (Math.random() * sum);
for ( int j = 0 ; j < props.length ; j++ ) {
if ( rand - props[j] <= 0 ) {
counts[j] = counts[j] + 1;
}
}
}
for ( int j = 0 ; j < props.length ; j++ ) {
System.out.println( "count " + j + "=" + counts[j] );
}
}
Depending on the test run it produces results like:
count 0=14
count 1=25
count 2=25
count 3=25
count 4=50