## Friday, 20 April 2012

### Modulus for previous array index

In JavaScript, C and C++, x % y will return a negative number if x is negative. This isn't what you want if you're trying to wrap around an array index (for example). Fortunately there's a nice solution. Instead of writing something like this:

  int prev(int x, int N) {
int prevX = (x - 1) % N;
if (prevX < 0)
prevX = N - 1;
return prevX;
}

you can simply write:
  int prev(int x, int N) {
return (x + N - 1) % N;
}


and let the magic of modular arithmetic do its work. This works for unsigned integers too.