如何递归地嵌套for循环? [英] How to make n nested for loops recursively?
问题描述
我有一个必须执行以下操作的方法:
I have a method that must do the following:
for (int a01 = 1; a01 <= 25; a01++) {
for (int a02 = a01 + 1; a02 <= 25; a02++) {
for (int a03 = a02 + 1; a03 <= 25; a03++) {
...
System.out.println(a01 + "," + a02 + "," + ... + "," + a015);
}
}
}
我想指定嵌套的数量(在上面的例子中,我想要15嵌套)。
有没有办法在这里使用递归编程?
I'd like to specify the number of nested for's (in the case above, I want 15 nested for's). Is there a way to use recursive programming here?
推荐答案
是的。这可以通过递归编程来执行。
Yes. This can be performed by recursive programming.
我假设您不喜欢在源代码中嵌套这些嵌套 - 就像在您的示例中一样,因为这是非常难看的编程 - 就像评论员解释一样。
I assume you do not like to WRITE DOWN these nested for's in source code - as in your example, because this is really ugly programming - like the commentors explain.
以下(伪类Java)代码说明了这一点。我假设嵌套的固定深度。那么你实际上喜欢循环一个维度深度的整数向量。
The following (pseudo Java-like) code illustrates it. I assume a fixed depth for the nesting. Then you actually like to loop over an integer vector of dimension depth.
int[] length = new int[depth];
int[] counters = new int[depth];
数组计数器
必须初始化为0( Arrays.fill(counter,0)
)。必须将数组 length
初始化为相应for循环的迭代次数。
The array counters
has to be initialised to 0 (Arrays.fill(counters,0)
). The array length
has to be initialised to the number of iterations for the respective for loop.
我假设你喜欢在内循环中执行某个操作。我将这个
称为 performOperation(int [] counter);
- 它取决于多维计数器,即外部的计数器。
I assume that you like to perform a certain operation within the inner loop. I will call this
performOperation(int[] counters);
- it depends on the multi-dimensional counter, i.e. the counters of the outer for's.
然后你可以通过调用
nestedLoopOperation(counters, length, 0);
其中
void nestedLoopOperation(int[] counters, int[] length, int level) {
if(level == counters.length) performOperation(counters);
else {
for (counters[level] = 0; counters[level] < length[level]; counters[level]++) {
nestedLoopOperation(counters, length, level + 1);
}
}
}
在你的情况下你的系统。 out.println()将
In your case your System.out.println() would be
performOperation(int[] counters) {
String counterAsString = "";
for (int level = 0; level < counters.length; level++) {
counterAsString = counterAsString + counters[level];
if (level < counters.length - 1) counterAsString = counterAsString + ",";
}
System.out.println(counterAsString);
}
这篇关于如何递归地嵌套for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!