3

I am looking 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 value 3 indexes ahead of it. Of course, this runs into an out of range exception once i+3>8.

What I'd like to do is if the the desired index is out of range then loop the index values back around 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 whatever means, 1, and then when i = 8, and i+3 = 11, I want i+3 to become 2.

So, the index pairs being evaluated would be something like:

i , i+3

0 3

1 4

2 5

3 6

4 7

5 8

6 0

7 1

8 2

how can I go about doing this?

Thanks for any help.

Christos
  • 53,228
  • 8
  • 76
  • 108
bababaram
  • 35
  • 5

2 Answers2

4

Use the modulo operator like this:

if (arr[i] == arr[(i + 3) % arr.Length]) { return true; }
Lucero
  • 59,176
  • 9
  • 122
  • 152
3

You could try the following expression inside your if statement.

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

The % Operator

Divides the value of one expression by the value of another, and returns the remainder.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • @Johnbot My bad...Thanks, I corrected the link. However, regarding the name, I don't think is wrong we call it Modulus operator. You will find with a bit googling this term also be used as the term remainder operator. – Christos Apr 09 '17 at 17:11
  • [This answer](http://stackoverflow.com/a/13683709) shows the difference between the two and is also applicable to C#. – Johnbot Apr 09 '17 at 17:19