Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap negative index to size of array [duplicate]

Tags:

c++

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
like image 540
Anonymous Entity Avatar asked May 07 '17 03:05

Anonymous Entity


1 Answers

You want the modulo operator with floored division.

int mod_floor(int a, int n) {
    return ((a % n) + n) % n;
}
like image 131
Joseph Thomson Avatar answered Nov 10 '22 12:11

Joseph Thomson