Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to achieve a simple algorithm

Tags:

java

c

algorithm

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.

  • A=30% possibilities
  • B=50% possibilities
  • C=20% possibilities

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?

like image 392
NullPointerException Avatar asked Jul 27 '26 04:07

NullPointerException


1 Answers

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
like image 197
yurib Avatar answered Jul 29 '26 19:07

yurib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!