如何遍历数组并在特定索引处停止。

huangapple go评论80阅读模式
英文:

How do I loop through an array and stop at a certain index

问题

所以,我有一个由7个数字组成的数组,从0到6。我想要循环遍历它一定次数,并在特定的索引或数字处停止。例如,程序从0开始,我希望循环12次,并且程序输出为4。另一个例子,程序从索引2开始循环10次。输出应该是索引5。我应该如何实现这个,这种操作是否可行?

英文:

So, I have an array of 7 numbers, 0-6. I want to loop through it for a certain amount of times and stop at a certain index or number. For instance, the program starts at 0 and I want to loop it 12 times and have the program output 4. Another instance, the program starts at index 2 and loops 10 times. The output should be index 5. How do I do this and is it possible?

答案1

得分: 0

你可以使用一个简单的循环来控制如何遍历数组。

示例:

int arr[]; // 我们的数组
int t; // 遍历数组的次数
/**
* 一些设置 t 值和填充 arr 的代码
**/

int index = 0; // 最终的索引。初始值为 0,以防 t <= 0 的情况

for (int i = 0; i < t; ++i) {
   if (index == arr.length) {index = -1;} // 设为 -1,这样我们就不需要有 else 分支
   ++index;
}

如果你想从数组中的某个不同于 0 的位置开始,只需在循环之前创建一些代码来设置 index,并记得检查 index 是否小于数组长度。

英文:

You could use a simple loop that controls how you cycle through the array.

Example:

int arr[]; // Our array
int t; // How much to cycle through the array
/**
* Some code to set a value for t and fill arr
**/

int index = 0; // The final index. Initally 0 to prevent undefined case  t &lt;= 0

for (int i = 0; i &lt; t; ++i) {
   if (index == arr.lenght) {index = -1;} // -1 so whe don&#39;t need to have an else clause
   ++index;
}

If you want to start in a position different than 0 in the array just create some code to set index before the loop and remember to check if index is less than the array lenght

答案2

得分: 0

我认为你正在寻找取模(%)运算符。这使你可以跳过循环,直接跳到最终的索引项。这个操作是恒定的,如果你不必实际遍历索引直到达到最终数字,那么应该优先使用这种方法。

对于你的两个例子,你可以看到每种情况下有两个打印语句:

class Main {
  public static void main(String[] args) {
    int arr[] = {0,1,2,3,4,5,6};
    int n = arr.length;
    int t = 12;
    //情况 1
    System.out.println(arr[t%n]);

    //情况 2
    int index = 2;
    t = 10;
    System.out.println((t + index)%n);
  }
}
英文:

I think you are looking for the modulo % operator. This allows you to skip the loop and immediately land on the final index entry. This operation is constant and should be preferred if you dont have to actually cycle through the indeces until you land on the final number.

For you two examples you can see two print statements for each case:

class Main {
  public static void main(String[] args) {
    int arr[] = {0,1,2,3,4,5,6};
    int n = arr.length;
    int t = 12;
    //case 1
    System.out.println(arr[t%n]);

    //case 2
    int index = 2;
    t = 10;
    System.out.println((t + index)%n);
  }
}

答案3

得分: 0

> "If the program (iterations) starts at 0 (index) and I want to
> loop it 12 times and have the program output 4".

Okay, I get that. You start your count as literal 1 from index 0:

1  2  3  4  5  6  7  8  9  10  11  12   (on the 12th iteration starting from Index 0)
-------------------------------------
0  1  2  3  4  5  6  0  1  2   3   4    (element value at index)
-------------------------------------
0  1  2  3  4  5  6  0  1  2   3   4    (array index)

> "Another instance, the program starts at index 2 and loops 10
> times. The output should be index 5".

This one confuses me:

      1  2  3  4  5  6  7  8  9  10     (on the 10th iteration starting from Index 2)
-----------------------------------
0  1  2  3  4  5  6  0  1  2  3  4      (element value at index)
-----------------------------------
0  1  2  3  4  5  6  0  1  2  3  4      (array index)

The output should be index 4 as well, not index 5.

Anyway, here's another way this can be accomplished:

int startIndex = 0;                     // The INDEX value to start iterations from.
int loopNumOfTimes = 12;                // The literal number of desired iterations.
int[] array = {0, 1, 2, 3, 4, 5, 6};    // The Integer Array (length 7).
int counter = 0;                        // A counter used to count literal iterations.
int i;                                  // Declared outside of loop so its value can be used.
// Iterate through the Array
for (i = startIndex; i < array.length; i++) {
    counter++;  // Increment counter.
    // Have we reached the desired number of iterations?
    if (counter == loopNumOfTimes) {
        // Yes...Break out of loop.
        break;
    }
    /* Reset the 'for' loop if we've reached actual array length (length minus 1).
       i++ in the 'for' loop is automatically applied once the first iteration is 
       complete and every iteration thereafter as long as 'i' remains less than 
       the literal length of the array. Because we are applying a value change to 
       'i' so as to start the loop from 0 again (a loop reset), the i++ will be 
       immediately applied, which takes 'i' to 1 instead of the desired 0. This 
       is no good, so we set 'i' to -1. That way when i++ is applied, 'i' is set to 
       0 and iterations start again from that index value.                  */
    if (i == (array.length - 1)) {
        i = -1;
    }
}

// Display the Array element value located at index 'i'.
System.out.println(array[i]);

In the above code, you can see that the Start Index (startIndex) is 0, and the Desired Number Of Loops (iterations) held in the loopNumOfTimes variable is 12. The output to the console window will be: 4.

If you change the startIndex value to 2 and the loopNumOfTimes value to 10, then the console window output will be: 4.

英文:

> "If the program (iterations) starts at 0 (index) and I want to
> loop it 12 times and have the program output 4".

Okay, I get that. You start your count as literal 1 from index 0:

1  2  3  4  5  6  7  8  9  10  11  12   (on the 12th iteration starting from Index 0)
-------------------------------------
0  1  2  3  4  5  6  0  1  2   3   4    (element value at index)
-------------------------------------
0  1  2  3  4  5  6  0  1  2   3   4    (array index)

> "Another instance, the program starts at index 2 and loops 10
> times. The output should be index 5".

This one confuses me:

      1  2  3  4  5  6  7  8  9  10     (on the 10th iteration starting from Index 2)
-----------------------------------
0  1  2  3  4  5  6  0  1  2  3  4      (element value at index)
-----------------------------------
0  1  2  3  4  5  6  0  1  2  3  4      (array index)

The output should be index 4 as well, not index 5.

Anyway, here's another way this can be accomplished:

int startIndex = 0;                     // The INDEX value to start iterations from.
int loopNumOfTimes = 12;                // The literal number of desired iterations.
int[] array = {0, 1, 2, 3, 4, 5, 6};    // The Integer Array (length 7).
int counter = 0;                        // A counter used to count literal iterations.
int i;                                  // Decalred outside of loop so its value can be used.
// Iterate through the Array
for (i = startIndex; i &lt; array.length; i++) {
    counter++;  // Increment counter.
    // Have we reached the desire number of iterations?
    if (counter == loopNumOfTimes) {
        // Yes...Break out of loop.
        break;
    }
    /* Reset the &#39;for&#39; loop if we&#39;ve reached actual array length (length minus 1).
       i++ in the &#39;for&#39; loop is automatically applied once the first iteration is 
       complete and every iteration thereafter as long as &#39;i&#39; remains less than 
       the literal length of the array. Because we are applying a value change to 
       &#39;i&#39; so as to start the loop form 0 again (a loop reset) the i++ will be 
       immediately be applied which takes &#39;i&#39; to 1 istead of the desired 0. This 
       is no good so we set &#39;i&#39; to -1 that way when i++ is applied &#39;i&#39; is set to 
       0 and iterations start again from that index value.                  */
    if (i == (array.length - 1)) {
        i = -1;
    }
}
    
// Display the Array element value located at index &#39;i&#39;.
System.out.println(array[i]);

In the above code you can see that the Start Index (startIndex) is 0 and the Desired Number Of Loops (iterations) held in the loopNumOfTimes variable is 12. The output to console window will be: 4.

If you change the startIndex value to 2 and the loopNumOfTimes value to 10 then the console window output will be: 4.

huangapple
  • 本文由 发表于 2020年9月20日 10:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63975032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定