Question

How can i do that? Let k an integer given for the user, i need "dynamically bulid" a nested loop of k levels, example:

if k = 5, then:

int[] a = new int[k];
for(int i=0; i<256; i++){
    for(int j=0; j<256; j++){
        for(int ke=0; ke<256; ke++){
            for(int l=0; l<256; l++){
                for(int m=0; m<256; m++){
                    a[0] = i;
                    a[1] = j;
                    a[2] = ke;
                    a[3] = l;
                    a[4] = m;
                    if (isCap(a)) //do something;
                }
            }
        }
    }
}

but if k = 3, then:

int[] a = new int[k];
for(int i=0; i<256; i++){
    for(int j=0; j<256; j++){
        for(int ke=0; ke<256; ke++){
            a[0] = i;
            a[1] = j;
            a[2] = ke;
            if (isCap(a)) //do something;                
        }
    }
}
Était-ce utile?

La solution

Seems that you have task to generate all k-coordinate cortages where k beetwen 0(inclusive) and 256(exclusive) and check them with your function isCap(). I advice you to write two function: increment cortage: inc([0,0,0,0,0]) = [0,0,0,0,1] or inc([12,13,15,5,255]) = [12,13,15,6,0]

and check function test if cortage is maximal. In your case :

boolean isCortageMaximum(a){
      return a == [255,255,255,255,255];
}

and then your loop would be following:

while(!isCortageMaximum(a)){
   if(isCap(a){
     //your actions here
   }
   inc(a);
}

Autres conseils

This is what recursion is for.

void recursiveInteration(int[] a, int currentIndex) {
   if (currentIndex <0) {
     //do something with a
     return;
   }
   for (int i=0; i< 256; ++i) {
     a[currentIndex] = i;
     recursiveInteration(currentIndex-1);
   }
}

And you'd use it as follows:

recursiveInteration(a, 5);

Using recursion:

int[] a = new int[k];
loop(256,0,a);

void loop(int length, int k, int[] a){
  if(k<a.length) // the array determines the maximum depth, you could pass the size instead
    for(int i=0; i<length; i++) {
      loop(length,k+1,a);
      a[k] = i;
      if(k==a.length-1){ // this will only execute in the innermost loop
        if (isCap(a)) doSomething();
      }
    }
}

You could also write it as:

void loop(int length, int k, int[] a){
  if(k<a.length)
    for(int i=0; i<length; i++) {
      loop(length,k+1,a);
      a[k] = i;
    }
  else if (isCap(a)) doSomething();
}

Please debug the code above if you need to use it in production, I haven't tested it, but you get the concept.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top