我有一个包含 1 2 3 4 5 值的数组。
array a = [ 1 , 2, 3, 4, 5]
现在我想以循环方式遍历它。
就像我想打印 2 3 4 5 1 或 3 4 5 1 2 或 5 1 2 3 4 等等。
任何算法关于这个?
Edit:我想以循环方式打印所有组合。我不想在初始阶段说明起点。
int start = ...
for (int i = 0; i < a.length; i++) {
System.out.println(a[(start + i) % a.length]);
}
(If you want to iterate the array backwards from start
, change start + i
to start - i + a.length
in the array subscript expression. The + a.length
is needed because, in Java, x % y
is negative when x
is negative; see Best way to make Java's modulus behave like it should with negative numbers? https://stackoverflow.com/questions/4412179)
我应该注意,就执行速度而言,这可能不是表达循环的最有效方式。不过,差别很小,并且最有可能无关紧要.
更相关的一点是是否使用%
这样可以提供更具可读性的代码。我认为确实如此,但也许那是因为我以前见过/使用过这个特定的习语。也许有必要发表评论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)