在Java中,我有整数d
等于2, 3, 4, ..., dmax
以下一般代码 - 高达最大数目dmax : d < dmax
(因此该代码是在该范围内重复的d
每个值):系列嵌套循环的且无需递归
// d is the number of wrapper loops
int[] ls = new int[d];
...
// let ls array be filled with some arbitrary positive numbers here
...
// first wrapper loop
for (int i1 = 0; i1 < ls[0]; i1++) {
...
// last wrapper loop
for (int id = 0; id < ls[d - 1]; id++) {
// internal loop
for (int j = id + 1; j < ls[d - 1]; j++) {
myCode();
}
}
...
}
在d = 3
情况下,它看起来像:
int ls = new int[3];
ls[0] = 5; ls[1] = 7; ls[2] = 5;
for (int i1 = 0; i1 < ls[0]; i1++) {
for (int i2 = 0; i2 < ls[1]; i2++) {
for (int i3 = 0; i3 < ls[2]; i3++) {
for (int j = i3 + 1; j < ls[2]; j++) {
myCode();
}
}
}
}
我要收集所有重复的代码到一个单一的广义之一。为了这个目的,我可以使用while
循环和递归象下面这样:
int d = 2, dmax = 10;
while (d < dmax) {
// in algorithm ls is pre-filled, here its length is shown for clearance
int[] ls = new int[d];
for (int i = 0; i < ls[0]; i++) {
doRecursiveLoop(1, d, -1, ls);
}
d++;
}
doRecursiveLoop(int c, int d, int index, int[] ls) {
if (c < d) {
for (int i = 0; i < ls[c]; i++) {
// only on the last call we give the correct index, otherwise -1
if (c == d - 1) index = i;
doRecursiveLoop(c + 1, d, index, ls);
}
} else {
for (int j = index + 1; j < ls[d - 1]; j++) {
myCode();
}
}
}
任何人能提供一些线索,以动态地发生,而不递归嵌套循环我将如何处理这个问题?
的可能的复制[C++:嵌套for循环(没有递归)的动态数](http://stackoverflow.com/questions/ 18732974/c-dynamic-number-of-nested-for-loops-without-recursion) – 2016-04-20 08:25:03
答案#1:http://stackoverflow.com/a/30290814/864113 答案#2:http://stackoverflow.com/a/18733552/864113 – 2016-04-20 08:34:20