I need to generate some random booleans. However I need to be able to specify the probability of returning true
. As a results doing:
private R
Your way is probably better, code golf-wise, but another way to do it is like this:
public boolean getRandomBoolean() {
Random random = new Random();
//For 1 in 5
int chanceOfTrue = 5;
if (random.nextInt(chanceOfTrue) == 0) {
return true;
} else {
return false;
}
}
Or for 2 in 5, try this:
public boolean getRandomBoolean() {
Random random = new Random();
//For 2 in 5
int chanceOfTrue = 5;
int randInt = random.nextInt(chanceOfTrue);
if (randInt == 0 || randInt == 1) {
return true;
} else {
return false;
}
}
Here's what I'm using. Very similar to FracturedRetina's answer.
Random random = new Random();
// 20% chance
boolean true20 = (random.nextInt(5) == 0) ? true : false;
// 25% chance
boolean true25 = (random.nextInt(4) == 0) ? true : false;
// 40% chance
boolean true40 = (random.nextInt(5) < 2) ? true : false;