在Java中推广for循环

kla*_*ann 5 java for-loop multidimensional-array

我真的不知道如何描述我的问题,所以我只是展示一个代码示例:

int[][][] mat;
int n;
int specificValue;

for (int i = 0; i < n; i++) {
    if(mat[i][n-i][3] != specificValue) {
        doStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在查找3d数组中的Integer值.对于每个领域,我必须使用以下其中一个:

  • 从零到n的计数器
  • 计数器从n运行到零
  • 一个固定的价值

所以我试图构建一个方法,可以避免我写这个循环大约20次,但我失败了,所以这就是我需要帮助的地方.我的想法是这样的:

search(Loop.UP, Loop.DOWN, Loop.FIXED);
Run Code Online (Sandbox Code Playgroud)

其中"Loop"将是一个表示我的可能性的枚举,但我不知道如何实现它,或者如果在Java中甚至可以在不对每种可能的组合进行硬编码的情况下实现它.

希望你能帮忙:)


好的,更具体的...我的设置我正在通过这个3d数组绘制一个矢量,一个特定的对角线,我想知道这个矢量上的值是什么,只有这个矢量.

并且因为绘制这样一个向量的可能性不止一个,我想有一个更通用的方法来获取这些值.我的搜索可能就像这样简单

search(Loop.UP, Loop.FIXED, Loop.FIXED);   // one plane
Run Code Online (Sandbox Code Playgroud)

这将是一个简单的for循环与一个计数器,但也

search(Loop.DOWN, Loop.UP, Loop.UP);   // through all three planes
Run Code Online (Sandbox Code Playgroud)

tot*_*to2 5

Path pathX = new Path.Up();
Path pathY = new Path.Down(n);
Path pathZ = new Path.Fixed(3);

for (int i = 0; i < n; i++) {
    if(mat[pathX.pos(i)][pathY.pos(i)][pathZ.pos(i)] != specificValue) {
        doStuff();  
    }
}
Run Code Online (Sandbox Code Playgroud)

哪里

public interface Path {
    public int pos(int i);

    public static class Up implements Path {
         @Override public int pos(int i) { return i; }
    }

    public static class Down implements Path {
         private int n;
         public Down(int n) { this.n = n; }
         @Override public int pos(int i) { return n - i - 1; }
    }

    public static class Fixed implements Path {
         private int v;
         public Down(int v) { this.v = v; }
         @Override public int pos(int i) { return v; }
    }
Run Code Online (Sandbox Code Playgroud)

因为我没有使用枚举Down取决于nFixed一些价值.