I want to generate random numbers, but don't want them to be from exclude
array. Here is my code.
public int generateRandom(int start, int end, ArrayList<Integer> exclude) {
Random rand = new Random();
int range = end - start +1 - exclude.size();
int random = rand.nextInt(range) + 1;
for(int i = 0; i < exclude.size(); i++) {
if(exclude.get(i) > random) {
return random;
}
random++;
}
return random;
}
I use this function in a while loop, and during each iteration I add a new value to exclude
.
Sometimes it returns numbers that belong to exclude
. What's the problem?
math. random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can't exclude a number, so your best bet would be to do randomise again until the result is not 0.
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
this worked for me:
public int randomInt(int start, int end, int... exception) {
int result = -1;
Random rand = new Random();
int range = end - start + 1;
boolean equals = true;
while(equals) {
result = rand.nextInt(range);
boolean differentOfAll = true;
for(int i : exception) {
if(result==i) {
differentOfAll = false;
break;
}
}
if(differentOfAll) {
equals = false;
}
}
return result;
}
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