Today I created a function which generates a random
number (0, 1, 2 or 3).
But I want yo have a percetage function.
I would like to apply a percentage to every chance to which the generated numbers fall.
Example: 0 will have 60% chance of being drawn, the number 1 19%, ...
public void GenerGame(){
Random r = new Random();
int game = r.nextInt(max - min +1);
if (game == 0){
// do something
}
else if (game == 1){
// do something
}
else if (game == 2){
// do something
}
else {
// do something
}
}
Can I do it by using Random
?
You can definitely do this by re-thinking your RNG.
If you change the random generation range to 0-99, you can think of this as a range of percentages produced, and hence prescribe various behaviors in those ranges.
public void GenerGame(){
Random r = new Random();
int game = r.nextInt(100);
if (game < 60){ // 60%
// do something
}
else if (game < 79){ // 19%
// do something
}
else if (game < 93){ // 14%
// do something
}
else { // 7%
// do something
}
}
You could change the precision to tenths of a percent by boosting the range to 0-999.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With