I have N options, between 1 and thousands. For example, I will explain it with 3 options, but I need this algorithm to work for N options.
I need to get randomly one of these three options, but according to the probabilities.
I achieved it by generating a random number between 0 and 100, and I'm doing some heavy and ugly code to know when the number is between 0 and the A possibilities number, between the A possibilities and the B possibilities, etc.
Do you know a better way to do this?
choose a random number in the range you need, start subtracting the probability of each option from that number until you reach 0. the last probability you subtracted is what you want.
int[] possibilities = new int[] {20,50,30};
Random rand = new Random();
int r = rand.nextInt(100);
int i = 0;
for (i=0;i<possibilities.length; i++) {
r -= possibilities[i];
if (r <= 0)
break;
}
System.out.println(i); // the index of the possibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With