有没有办法在Java中做n级嵌套循环?

2022-09-01 11:15:30

换句话说,我能做这样的事情吗?

for() {
    for {
       for {
       }
    }
}

除了N次?换句话说,当调用创建循环的方法时,它被赋予一些参数N,然后该方法将创建N个嵌套在另一个循环中的N个?

当然,这个想法是应该有一种“简单”或“通常”的方式来做到这一点。我已经有一个非常复杂的想法。


答案 1

jjnguy是对的;递归允许您动态创建可变深度嵌套。但是,如果不进行更多的工作,您将无法访问来自外部层的数据。“内联嵌套”情况:

for (int i = lo; i < hi; ++i) {
    for (int j = lo; j < hi; ++j) {
        for (int k = lo; k < hi; ++k) {
            // do something **using i, j, and k**
        }
    }
}

将变量 、 和 保持在最内层主体使用的范围内。ijk

这里有一个快速的技巧来做到这一点:

public class NestedFor {

    public static interface IAction {
        public void act(int[] indices);
    }

    private final int lo;
    private final int hi;
    private final IAction action;

    public NestedFor(int lo, int hi, IAction action) {
        this.lo = lo;
        this.hi = hi;
        this.action = action;
    }

    public void nFor (int depth) {
        n_for (0, new int[0], depth);
    }

    private void n_for (int level, int[] indices, int maxLevel) {
        if (level == maxLevel) {
            action.act(indices);
        } else {
            int newLevel = level + 1;
            int[] newIndices = new int[newLevel];
            System.arraycopy(indices, 0, newIndices, 0, level);
            newIndices[level] = lo;
            while (newIndices[level] < hi) {
                n_for(newLevel, newIndices, maxLevel);
                ++newIndices[level];
            }
        }
    }
}

该接口规定了受控操作的角色,该操作将索引数组作为其方法的参数。IActionact

在此示例中,的每个实例都由构造函数配置,其中包含迭代限制和最里面的级别要执行的操作。该方法的参数指定嵌套的深度。NestedFornFor

下面是一个示例用法:

public static void main(String[] args) {
    for (int i = 0; i < 4; ++i) {
        final int depth = i;
        System.out.println("Depth " + depth);
        IAction testAction = new IAction() {
            public void act(int[] indices) {
                System.out.print("Hello from level " + depth + ":");
                for (int i : indices) { System.out.print(" " + i); }
                System.out.println();
            }
        };
        NestedFor nf = new NestedFor(0, 3, testAction);
        nf.nFor(depth);
    }
}

以及其执行的(部分)输出:

Depth 0
Hello from level 0:
Depth 1
Hello from level 1: 0
Hello from level 1: 1
Hello from level 1: 2
Depth 2
Hello from level 2: 0 0
Hello from level 2: 0 1
Hello from level 2: 0 2
Hello from level 2: 1 0
Hello from level 2: 1 1
Hello from level 2: 1 2
Hello from level 2: 2 0
Hello from level 2: 2 1
Hello from level 2: 2 2
Depth 3
Hello from level 3: 0 0 0
Hello from level 3: 0 0 1
Hello from level 3: 0 0 2
Hello from level 3: 0 1 0
...
Hello from level 3: 2 1 2
Hello from level 3: 2 2 0
Hello from level 3: 2 2 1
Hello from level 3: 2 2 2

答案 2

听起来你可能想研究递归。


推荐