'How to exclude a specific number from random method while filling array
I'm looking for a solution for exclude one number from Random method filling an array. I wrote a following code but instead of using "i--" I would like to use while statement. Does anyone have an idea how to handle it?
Random random = new Random();
int[] tab = new int[10];
for(int i=0 ; i<10 ; i++) {
int randomNumber = random.nextInt(11);
if(randomNumber == 5) {
i--;
continue;
}
tab[i] = randomNumber;
}
Solution 1:[1]
You could generate a random integer between 0 (inclusive) to 10 (exclusive) and then "shift" the values to omit 5.
Random random = new Random();
for (int i=0 ; i<10 ; i++) {
int randomNumber = random.nextInt(10);
if (randomNumber < 5) {
tab[i] = randomNumber;
}
else {
tab[i] = randomNumber + 1;
}
}
(EDIT: Show full code including the loop.)
EDIT 2: OP wants a solution that regenerates randomNumber until it is not 5:
Random random = new Random();
for (int i=0 ; i<10 ; i++) {
int randomNumber;
while ((randomNumber.nextInt(11)) != 5) {
tab[i] = randomNumber;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
