<返回更多

如何简化多层嵌套for循环

2023-08-19  微信公众号  程序员长承
加入收藏

场景分析

如下代码是 6 层 for 循环。

ublic void forSix() {    String preFix = "101";    String postFix = "11";
    for (int i = 0; i < 2; i++) {        for (int j = 0; j < 2; j++) {            for (int k = 0; k < 2; k++) {                for (int l = 0; l < 2; l++) {                    for (int m = 0; m < 2; m++) {                        for (int n = 0; n < 2; n++) {                            // operation                            System.out.println(preFix+i+j+k+l+m+n+postFix);                        }                    }                }            }        }    }}

如果碰到更为复杂的应用场景,可能存在更深层次的嵌套 for 循环,如 10、13层等,乃至于更多。

如何简化 for 循环的层次?可以使用递归解决问题。

递归优化

ublic static final String PRE_FIX = "101";
public static final String POST_FIX = "11";
public final StringBuilder sb = new StringBuilder();
public void simpleFor(int level) {    if (level > 6) {        return;    }
    for (int i = 0; i < 2; i++) {        sb.Append(i);        if (level == 6) {            System.out.println(PRE_FIX + sb + POST_FIX);        }        simpleFor(level + 1);        sb.deleteCharAt(sb.length() - 1);    }}

新的问题

以上代码每一层 for 循环的数组都是相同,如果每一层需要循环的数组不同该怎么办?

可以使用 Map<Integer, Integer[]> 保存相关数组,索引为 level.

改进版递归代码

ublic static final String PRE_FIX = "101";
public static final String POST_FIX = "11";
public final StringBuilder sb = new StringBuilder();
public final Map<Integer, Integer[]> integerMap = new HashMap() {{   put(1, new Integer[]{0,1,2,3,4,5,6,7,8,9});   put(2, new Integer[]{0,1,2,3,4,5,6,7,8,9});   put(3, new Integer[]{0,1,2,3,4,5,6,7,8,9});   put(4, new Integer[]{0,1,2,3,4,5,6,7,8,9});   put(5, new Integer[]{0,1,2,3,4,5,6,7,8,9});   put(6, new Integer[]{0,1,2,3,4,5,6,7,8,9});}};
public void simpleForOptimize(int level) {    if (level == 7) {        return;    }    Integer[] integers = integerMap.get(level);    for (Integer integer : integers) {        sb.append(integer);        if (level == 6) {            System.out.println(PRE_FIX + sb + POST_FIX);        }        simpleForOptimize(level + 1);        sb.deleteCharAt(sb.length() - 1);    }}

 

关键词:for循环      点击(11)
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多for循环相关>>>