Overriding through an array

So let's say I have an array of length 5 (just call it myArray [5]). If I add 4 to myArray [3], such as myArray [3 + 4], how can I loop it through myArray again so that it becomes myArray [2]?

example)

myArray[3]

myArray[4]   //+1

myArray[0]   //+2

myArray[1]   //+3

myArray[2]   //+4

      

+3


source to share


3 answers


Just use the length of the array for the module operation:



int index = /* index you are using */;
myArray[index % myArray.length]

      

+4


source


You can use a module. index % myArray.length

like

int[] myArray = new int[10];
for (int i = 10; i < 20; i++) {
    System.out.println(i % myArray.length);
}

      



The output is 0 - 9 (inclusive).

+2


source


If you want to cycle through the array in a circular fashion, then the module %

is the path. If you combine this with Java 8 Streaming API: s the solution might look like this.

    int[] myArray = {1, 2, 3, 4, 5}; // Setup the array
    int startIndex = 3;              // Start index as per the OP example
    int addIndex = 4;                // Add as per the OP example

    // Loop via streams - no external looping
    IntStream.range(startIndex, startIndex + addIndex)
            .map(i -> myArray[i % myArray.length]) // circular loop
            .forEach(System.out::println /* Do your stuff */); // do your stuff

      

For more examples see this answer

+1


source







All Articles