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?

asked Mar 25, 2014 at 21:11
3
  • 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. Commented Mar 25, 2014 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<x<20) print(p[1]) Commented Mar 25, 2014 at 21:16
  • Possible duplicate of stackoverflow.com/questions/17250568/… Commented Mar 25, 2014 at 21:18

1 Answer 1

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.

answered Mar 25, 2014 at 21:18
Sign up to request clarification or add additional context in comments.

3 Comments

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 I've edited my answer to reflect that. Let me know if this is what you need.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.