java - How can a random value be spreaded with a given probability? -


for ai i'm using random values decide action perform next (only when there nothing rule based do). of actions should picked more others.

the idea define group of probabilities , pick action probs 2 twice action 1, action 4 5 times higher probability.

action prob 0         1 1         2 (twice 1) 2         2 3         2 4         5 (5 times morer 1) 

is there wellknown algorithm behaviour or more mathematical approach?

my test implementation awkward. prefer avoid inner loop.

public static void main(string[] args) {     int[] counts = new int[5];     int[] props = { 1 ,2 ,2 ,2 ,5 };     int sum = 0;     (int = 0; < props.length ; i++) {         sum += props[i];     }     ( int = 0 ; < 100 ; i++ ) {         int rand = (int) (math.random() * sum);         ( int j = 0 ; j < props.length ; j++ ) {             if ( rand - props[j] <= 0 ) {                 counts[j] = counts[j] + 1;             }         }     }     ( int j = 0 ; j < props.length ; j++ ) {         system.out.println( "count " + j + "=" + counts[j] );     } } 

depending on test run produces results like:

count 0=14 count 1=25 count 2=25 count 3=25 count 4=50 

you looking solve equation:

p0 + p1 + p2 + p3 + p4 = 1 p0 = p p1 = 2p p2 = 2p p3 = 2p p4 = 5p  

this set of linear equations , can solved pretty using linear algebra.

in example:

p + 2p + 2p + 2p + 5p = 1 12p = 1 p = 1/12 p0 = 1/12 p1 = p2 = p3 = 2/12 p5 = 5/12 

you can use single uniformly distributed number in [0,1) x chose event happens setting array:

aux[0] = 0 aux[i] = aux[0] + p_{i-1} 

so in example:

aux = [0,1/12,3/12,5/12,7/12,1] 

then, draw value x, , binary search on i find closest value higher x, , that's event.


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -