C # string array index values ​​back to beginning of array after index

I want to create a program like the following (C # btw):

int[] arr = new int[9]
//some code that puts values 1, 0, or 2 in each array element
for(int i = 0; i < arr.Length; i++)
{
    if (arr[i] == arr[i + 3]) { return true; }
}

      

So, for each value in the array, I am applying a formula that does something with that value and the index of the value 3 before it. Of course this happens out of range after i + 3> 8.

What I would like to do is that the desired index is out of range and then rounds the index values ​​back to the beginning of the array. So, in an array of length 9, where the last index is 8, if on a given loop i = 7 and i + 3, then = 10, I would like i + 3 to "become" by any means 1 and then when i = 8 and i + 3 = 11, i want i + 3 to become 2.

So the evaluated pairs of indices would be:

i, i + 3

0 3

fourteen

2 5

3 6

4 7

5 8

6 0

7 1

8 2

How can i do this?

Thanks for any help.

+3


source to share


2 answers


Use the modulo operator like this:



if (arr[i] == arr[(i + 3) % arr.Length]) { return true; }

      

+4


source


You can try the following expression inside your operator if

.

arr[i] == arr[(i + 3) % arr.Length];

      



% Operator

Splits the value of one expression by the value of another and returns the remainder.

+3


source







All Articles