[英]array logic : How can i arrange two array numbers
I have two arrays:我有两个数组:
int array1 [] = {1,2,3,4,5,6,7};
[This array can grow to huge numbers] [这个数组可以增长到巨大的数字]
int array2 [] = {1,2,3};
[Max it can have is 30 elements] [最多可以有 30 个元素]
array1 should be the parent loop and will have more elements than array2. array1 应该是父循环,并且比 array2 有更多的元素。 For example I have to arrange like below :
例如,我必须安排如下:
Expected result :预期结果 :
1-1 1-1
2-2 2-2
3-3 3-3
4-1 4-1
5-2 5-2
6-3 6-3
7-1 7-1
How can I proceed?我该如何继续?
You don't need a nested loop in this case;在这种情况下,您不需要嵌套循环; all you need is proper use of the modulus operator.
您所需要的只是正确使用模数运算符。
for (int i = 0; i < array1.length; i++) {
System.out.println(array1[i] + "-" + array2[i % array2.length]);
}
The reason this works is that the modulus operator maps very nicely to your problem.这样做的原因是模数运算符很好地映射到您的问题。 The operation you're trying to perform requires repeatedly iterating through a list (
array2
) and wrapping back to the beginning.您尝试执行的操作需要重复遍历列表 (
array2
) 并返回到开头。 The modulus operator is, in essence, a "wrapping" operator;取模运算符本质上是一个“包装”运算符; thinking incrementally, it allows you to go back to 0 every time you reach a certain number (in this case, the size of
array2
).循序渐进地思考,它允许您在每次达到某个数字(在本例中为
array2
的大小)时返回到 0。
So you have two sets, you want to loop through each element of the larger set (array1) and for each element of the set print the element, and the next element of set2 (array2).所以你有两个集合,你想遍历较大集合 (array1) 的每个元素,并为集合的每个元素打印元素,以及 set2 (array2) 的下一个元素。
I used an enhanced for loop , it loops over each element, and then modulus witch effectively limits i
to be less than the length of set2.我使用了增强的 for 循环,它循环遍历每个元素,然后模数有效地将
i
限制为小于 set2 的长度。 (remainder must be less than 3 if dividing by 3) (如果除以 3,余数必须小于 3)
This allows us to add one to i
using i++
and be assured that it will always loop back around to the first element as if the value were on a spinner .这允许我们使用
i++
将一个添加到i
并确保它将始终循环回到第一个元素,就好像该值在spinner 上一样。
int i = 0;
for( int value : array1 ) {
System.out.print( value + "-" + array2[i++ % array2.length] );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.