user3453281
user3453281

Reputation: 599

loaded dices (weighted random)

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?

Upvotes: 0

Views: 73

Answers (1)

Taj Morton
Taj Morton

Reputation: 1638

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.

Upvotes: 1

Related Questions