动态更改嵌套for循环的数量 [英] Dynamically change the number of nested for loops

查看:170
本文介绍了动态更改嵌套for循环的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是一个愚蠢的问题,但是我需要动态地更改循环的次数而不使用递归。



例如,如果n = 3,我需要3个嵌套for循环。

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

如果n = 5:

$ b pre $ (int l = 0; l for(int k = 0; k< size-2; k ++){
for (int m = 0; m // do something
}
}
}
}
}

有没有办法实现这个没有递归?
另一个问题:在Java中使用多个Dispatch?我正在尝试在ONE METHOD中编写一些东西,并且应该在不同的参数情况下运行不同的事件。注意:我只能有一种方法(部分问题),而且不能使用递归。

解决方案

想想你经历这个循环的次数。它看起来像(size!)/(size - n)!

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

}

for(int i = 0; i< numLoops; i ++){
// do something
}


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

For example, if n=3, I need 3 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 any way to achieve this without recursion? Another question: what is the use of Multiple Dispatch in Java? I'm trying to code something in ONE METHOD, and it should run different events in different cases of the parameter. NO IF STATEMENTS / TERNARY OPERATORS / CASES.

NOTE: I can ONLY have one method (part of the problem), and cannot use recursion. Sorry.

解决方案

Think about how many times you run through this loop. 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
}

这篇关于动态更改嵌套for循环的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆