Say for example I am given the number 3
. I then have to choose a random number from 0 to 3, but where 0 has a bigger chance of being chosen than 1, 1 has a bigger chance of being chosen than 2, and 2 has a bigger chance of being chosen than 3.
I already know that a percentage chance of choosing a specific number from 0 to 3 can kind of be achieved by doing the following:
double r = Math.random();
int n = 0;
if (r < 0.5) {
n = 0;
// 50% chance of being 0
} else if (r < 0.8) {
n = 1;
// 30% chance of being 1
} else if (r < 0.95) {
n = 2;
// 15% chance of being 2
} else {
n = 3;
// 5% chance of being 3
}
The problem is that the 3
can be anything. How can I do this?
Note: The numbers 0.5, 0.8 and 0.95 were arbitrarily chosen by me. I would expect those numbers to decrease so that the sum of all of them equals 1, and so that none of them are the same, if that is possible in some way.