I'm trying to mod an integer to get an array position so that it will loop round. Doing i %
arrayLength
works fine for positive numbers but for negative numbers it all goes wrong.
4 % 3 == 1
3 % 3 == 0
2 % 3 == 2
1 % 3 == 1
0 % 3 == 0
-1 % 3 == -1
-2 % 3 == -2
-3 % 3 == 0
-4 % 3 == -1
so i need an implementation of
int GetArrayIndex(int i, int arrayLength)
such that
GetArrayIndex( 4, 3) == 1
GetArrayIndex( 3, 3) == 0
GetArrayIndex( 2, 3) == 2
GetArrayIndex( 1, 3) == 1
GetArrayIndex( 0, 3) == 0
GetArrayIndex(-1, 3) == 2
GetArrayIndex(-2, 3) == 1
GetArrayIndex(-3, 3) == 0
GetArrayIndex(-4, 3) == 2
I've done this before but for some reason it's melting my brain today :(
For the more performance aware devs
A small performance comparison
As for performance cost of cast to uint have a look here
Adding some understanding.
By Euclidean definition the mod result must be always positive.
Ex:
Output:
Just add your modulus (arrayLength) to the negative result of % and you'll be fine.