Wrap negative index to size of array

c++

Solution

You want the modulo operator with floored division.

int mod_floor(int a, int n) {
    return ((a % n) + n) % n;
}

Problem

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 ```

Original source

Related problems