在 Java 中推广 for 循环
我真的不知道如何描述我的问题,所以我只展示一个代码示例:
int[][][] mat;
int n;
int specificValue;
for (int i = 0; i < n; i++) {
if(mat[i][n-i][3] != specificValue) {
doStuff();
}
}
我正在 3d 数组中查找整数值。对于每个字段,我必须使用其中一个:
- 从零运行到 n 的计数器
- 从 n 到零运行的计数器
- 固定值
所以我尝试构建一个方法,该方法可以使我免于编写此 for 循环大约 20 次,但我失败了,所以这就是我需要帮助的地方。我的想法是这样的:
search(Loop.UP, Loop.DOWN, Loop.FIXED);
其中“Loop”将是一个代表我的可能性之一的枚举,但我不知道如何实现它,或者这在Java中是否可能,而无需对每种可能的组合进行硬编码。
希望你能帮忙:)
好吧,更具体一点...通过我的设置,我正在通过这个 3d 数组绘制一个向量,具体来说是一条对角线,我想知道这个向量上的值是什么,并且 only< /strong> 在此向量上。
而且因为绘制这样的向量的可能性不止一种,所以我希望有一种更通用的方法来获取这些值。我的搜索可以很简单,就像
search(Loop.UP, Loop.FIXED, Loop.FIXED); // one plane
一个带有一个计数器的简单 for 循环一样简单,但也
search(Loop.DOWN, Loop.UP, Loop.UP); // through all three planes
I don't really know how to describe my issue, so I'll just show a code example:
int[][][] mat;
int n;
int specificValue;
for (int i = 0; i < n; i++) {
if(mat[i][n-i][3] != specificValue) {
doStuff();
}
}
I'm looking up Integer values in a 3d-array. For each field I have to use one of these:
- a counter running from zero to n
- a counter running from n to zero
- a fixed value
So i've tried to build a Method that would save me from writing this for loop about 20 times, but i failed, so that's where i need help. My idea was something like this:
search(Loop.UP, Loop.DOWN, Loop.FIXED);
where "Loop" would be an enum representing one of my possibilities, but I don't know how to implement it or if this is even possible in Java without hardcoding every possible combination.
Hope you can help :)
OK, more specific... with my setup i'm drawing a vector through this 3d-array, a diagonal to be specific and i want to know what values are on this vector and only on this vector.
And because there is more than one possibility to draw such a vector, i'd like to have a more general method to get to the values. My search could just be as simple as
search(Loop.UP, Loop.FIXED, Loop.FIXED); // one plane
which would be a simple for-loop with one counter, but also
search(Loop.DOWN, Loop.UP, Loop.UP); // through all three planes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没有使用枚举,
因为
Down
取决于n
和Fixed
取决于某个值。where
I didn't use an Enum because
Down
depends onn
andFixed
on some value.您可以使用索引列表。在 Python 中,它可能看起来像这样:
You could use a list of indices. In Python, it could look something like this:
目前我能想到的最好的办法是:
FIXED
是唯一需要索引的选项,因此被编码为索引。UP
和DOWN
不是索引,因此它们使用负数进行编码。用法类似于我的
System.out.println
示例,输出将是The best I can think of at the moment is this:
FIXED
is the only option which requires an index, and is thus encoded as an index.UP
andDOWN
are not indices, so they are encoded using negative numbers. Usage would go something likeWith my
System.out.println
example, the output would be