Java – dynamically change the number of nested for loops

I don't know if this is a stupid question, but I need to dynamically change the number of for loops without recursion

For example, if n = 3, I need three nested for loops

for(int i=0; i<size; i++){
   for(int j=0; j<size-1; j++){
       for(int k=0; k<size-2; k++){
          //do something
       }
   }
}

If n = 5:

for(int i=0; i<size; i++){
   for(int j=0; j<size-1; j++){
       for(int k=0; k<size-2; k++){
          for(int l=0; l<size-3; L++){
              for(int m=0; m<size-4; m++){
                  //do something
              }
          }
       }
   }
}

Is there a way to do this without recursion? Another question: what's the use of multiple dispatch in Java? I try to write code in a way that should run different events with different parameters If declaration / ternary operator / case

Note: I can only have one method (part of the problem) and can't use recursion i 'm sorry.

Solution

Think about how many times you go through this cycle It looks like (size!)/ (size – n)!:

int numLoops = 1;
for (int i = 0; i < n; i++) {
    numLoops*= (size - i);
}

for (int i = 0; i < numLoops; i++) {
    //do something
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>