gpt4 book ai didi

java - 嵌套 For 循环动态深度 Java

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:34:09 25 4
gpt4 key购买 nike

您好,我是编程新手并已注册到此论坛:)

因此,我创建了一个带有嵌套 for 循环的小程序,它打印出五个数字的所有组合,这些数字的值可以从 0 到 5。使用嵌套 for 循环可以正常工作。但是没有更清洁的解决方案吗?我尝试通过调用 for 循环本身来尝试它,但我的大脑没有得到解决方案.. :(

//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}

最佳答案

通常当人们尝试使用递归或函数时,使用循环更简单或更快。然而,在这种情况下,递归是与循环结合使用的更简单的选择。

public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}

关于java - 嵌套 For 循环动态深度 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13865235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com