java - Trying to achieve a simple algorithm -
java - Trying to achieve a simple algorithm -
i have n options, between 1 , thousands. example, explain 3 options, need algorithm work n options.
a=30% possibilities b=50% possibilities c=20% possibilitiesi need randomly 1 of these 3 options, according probabilities.
i achieved generating random number between 0 , 100, , i'm doing heavy , ugly code know when number between 0 , possibilities number, between possibilities , b possibilities, etc.
do know improve way this?
choose random number in range need, start subtracting probability of each alternative number until reach 0. lastly probability subtracted want.
int[] possibilities = new int[] {20,50,30}; random rand = new random(); int r = rand.nextint(100); int = 0; (i=0;i<possibilities.length; i++) { r -= possibilities[i]; if (r <= 0) break; } system.out.println(i); // index of possibility
java c algorithm
Comments
Post a Comment