Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If(something) re-do the for loop

Tags:

java

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;
}
like image 484
amirsoltani Avatar asked Jul 19 '26 13:07

amirsoltani


2 Answers

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:

  1. Choose a number R between 1-47 (the numbers 1-4, 6-8, 10-12, 14-50 are all equally probable)
  2. If R == 5 then R = 48
  3. else if R == 9 then R = 49
  4. else if R == 13 then R = 50

This can easily be made into a function where you pass a set of unwanted numbers.

like image 169
Ian Mc Avatar answered Jul 22 '26 02:07

Ian Mc


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;
}
like image 33
Antimony Avatar answered Jul 22 '26 03:07

Antimony