Reputation: 284
I was wondering how can I program a dice which has a greater chance to roll a 6? I've tried everything but I just cant figure the algorithm. The probability of six is given by the user.
I just don't now how to program random
which uses the given probability to roll a 6 or 1-5.
Upvotes: 0
Views: 852
Reputation: 644
Divide what remains of the interval (0,1) when you take out a region the size of the probability of six into 5 equal pieces and assign these regions to 1 - 5:
/**
* @param pSix probability that a six is returned
* @param rnd Random instance
* @return a random integer between 1 and 6 with 1-5 equiprobable and P(6) = pSix
*/
public int loadedDice(final double pSix, final Random rnd) {
final double pOther = (1d - pSix) / 5d;
final float val = rnd.nextFloat();
if (val < pSix) {
return 6;
}
return (int) Math.ceil((val - pSix) / pOther);
}
}
Upvotes: 2
Reputation: 7507
I would suggest using a percentage based scheme. let the user pick the probability of a six, in this example lets say 30%. Then choose a random number between 0-1.0 (which is what java's Random#nextFloat
does). If its below or equal to .3
, then make it a six, otherwise make it a 1-5.
Random r = new Random();
float probability = r.nextFloat(); // get a value between 0 and 1
if (probability < probabilityOfSix){
return 6;
} else {
return r.nextInt(4) +1;
}
Upvotes: 3
Reputation: 676
Let's say a 6 has twice the probability to appear. Get a random number from 1 through 7, if your result is either a 6 or a 7, then you have a 6.
Same thing for three times the probability. Fetch a random number from 1-8: 6, 7, and 8 become a 6.
Upvotes: 2