java中无递归处理变量嵌入循环的算法/模式

java中无递归处理变量嵌入循环的算法/模式,java,algorithm,loops,recursion,Java,Algorithm,Loops,Recursion,我正在寻找一种算法/模式来处理java中未定义数量的内部循环,而无需递归 我假设内部循环执行相同(或类似)的过程 每个循环根据外部循环生成/处理/存储数据。所以复杂性可能是指数级的 用法:例如组合数学。但我正在寻找一个通用的解决方案 一些示例(不符合要求): 嵌入但不可变:如果内部循环的数量已知: for (int i=0;...) { // process 1 for (int j=0;...) { // process 2 for (int

我正在寻找一种算法/模式来处理java中未定义数量的内部循环,而无需递归

我假设内部循环执行相同(或类似)的过程

每个循环根据外部循环生成/处理/存储数据。所以复杂性可能是指数级的

用法:例如组合数学。但我正在寻找一个通用的解决方案

一些示例(不符合要求):

嵌入但不可变:如果内部循环的数量已知

for (int i=0;...)
{
// process 1

    for (int j=0;...)
        {
    // process 2

        for (int k=0;...)
            {
            // process 3

            }
        }
}
多个循环,但未嵌入

for (int which_loop = 1; ...)
{
// LOOP which_loop

// Problem: loops are not embedded, then you cant reuse datas ...
}

一种方法是使迭代器实际上成为迭代器数组,并使用它进行计数

为了简单起见,让我们假设所有变量都增加到相同的数目(
n
),并且这些变量的数目是
num\u dimensions
。通过检查另一个数组而不是值
n
,可以轻松地放宽此假设

伪代码:

int[] arr = new int[num_dimensions];
int k = 0;
while (true) { 
  if (arr[k] == n) {  // go to next iterator
    k++;
    if (k > num_dimensions - 1) { // done!
      break;
    }
  } 
    if (k == 0) {
      process(arr); // do the process here. arr is the state of the iterators.
      arr[k]++;
    } else { 
      // increase the iterator and go back to the first iterator.
      for (int i = 0; i < k; i++) arr[i] = 0; 
      arr[k]++;
      k = 0;
    }


}
这种方法很有趣(我曾经在你的案例中使用过它!)。你认为这是唯一的一个(或者其他所有的都是等效的)?我不确定你的算法:你不能增加或减少k。
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111