0

I need to select one possible output based on probabilities. lets say I have

p[1]=20%
p[2]=40%
p[3]=15%
p[4]=25%

the size of p[] is a variable (in this case 4) and I know that together they sum to 100%. how to select one element from p in accordance to it's probability?

user3453281
  • 559
  • 5
  • 12
  • 2
    A first idea: create a random integer value between 1 and 100. Then check via `if/else` its value and set your array accordently. – pzaenger Mar 25 '14 at 21:14
  • the difficulty is that I do not know how many elements are in p[]. for this reason I cannot hardcode something like if (0 – user3453281 Mar 25 '14 at 21:16
  • Possible duplicate of http://stackoverflow.com/questions/17250568/randomly-choosing-from-a-list-with-weighted-probabilities – pjs Mar 25 '14 at 21:18

1 Answers1

1

The simplest way to use this is to use the Random.nextFloat() method for this, and then check which range the random number between 0-1 falls in.

Based on your question comments, you probably want something more like this:

Random r = new Random();
p[0]=0.2;
p[1]=0.4;
p[2]=0.15;
p[3]=0.25;

float myVal = r.nextFloat();
float probSum = 0.0;

for (int i = 0; i < p.length; p++) {
    probSum += p[i];
    if (myVal <= probSum) {
        return i;
    }
}
return p.length-1;

Obviously you can pretty this up, but this is a general idea that should work.

Taj Morton
  • 1,588
  • 4
  • 18
  • 26
  • I cannot code it like this because I do not know how many elemnts are in p[], so I wouldnt know how many else(if) brackets I need. what I know is that I have n elements and their probability add up to 100%. I also know their individual probability – user3453281 Mar 25 '14 at 21:22
  • @user3453281 I've edited my answer to reflect that. Let me know if this is what you need. – Taj Morton Mar 25 '14 at 21:22
  • ooh this is pretty and is very much looks like it does what I need. I sum their individual probability until my I get to my random number. yeah that should works. thanks friend. – user3453281 Mar 25 '14 at 21:26