This one is very simple and basic, but for some reason I cant get it right. So I'm making a for loop and inside the for loop generating random numbers, but I want to eliminate some numbers by redoing the for loop when those numbers come up. how should I do it and whats my mistake. Thank you in advance.
How I did it:
int[] array= new int[6];
for(int i=0;i<array.length;i++){
Random rand = new Random();
int n = rand.nextInt(50) + 1;
if(n==5 || n==9 || n==13){
i--;
return;
}
array[i]=n;
}
This is an interesting post. Just want to chime in and share what my first instinct is. Perhaps it is not conventional.
There is no reason to roll again if you hit upon 5, 9, 13. The approach can be deterministic
Algorithm:
This can easily be made into a function where you pass a set of unwanted numbers.
I think the cleanest way would be to have an inner loop that loops until you get an acceptable number. That way the inner loop could be later factored into a function if necessary. I also moved the random number generator initialization out of the loop, since I assume that's what was intended.
Random rand = new Random();
for (int i = 0; i < array.length; ++i) {
int n = rand.nextInt(50) + 1;
while (n == 5 || n == 9 || n == 13) {
n = rand.nextInt(50) + 1;
}
array[i] = n;
}
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