Given an array of length size
and an index n
to that array, how can I wrap the index such that it is always within size-1
? For positive numbers its simply n % size
, but how to achieve backwards wrap around when n
is negative?
What I've come up with:
int wrap(int size, int n) {
if (n >= 0)
return n % size;
else
return abs(size + n) % size;
}
But this only works for n <= size
; How to make it work for any n
?
Expected output:
wrap(4, -1) == 3
wrap(4, -2) == 2
wrap(4, -3) == 1
wrap(4, -4) == 0
wrap(4, -5) == 3
wrap(4, -6) == 2
wrap(4, -7) == 1
wrap(5, -8) == 0
You want the modulo operator with floored division.
int mod_floor(int a, int n) {
return ((a % n) + n) % n;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With