在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();

        }
    }

}

有人可以阐明我如何解决动态生成的嵌套循环而无需递归的问题吗?

最佳答案

您实际上在这里有tail recursion。任何尾递归函数都可以使用循环将trivially be converted变成迭代函数。

例如:

void foo() {
    // ... Stuff ...

    if (someCondition) {
        foo();
    } else {
        bar();
    }
}

变成:
void foo() {
    while (someCondition) {
        // ... Stuff ...
    }
    bar();
}

08-04 16:38