Search code examples
c++modular-arithmetic

Modular operation (%) provides false output


With a function, getNextIdx, I want to receive a new index for an array that depends on the current index and the value of the array at that index.

I want the function to return the new index by summing the current index with the value of the array at that index, modular to the array size.

#include<vector> 
using namespace std;

int getNextIdx(int currentIdx, vector<int> array) {
    int jump = array[currentIdx];
    int nextIdx = (currentIdx + jump) % array.size();
    
    return (nextIdx >= 0) ? nextIdx : nextIdx + array.size();
}
int main() {
    vector<int> test = {2, 3, 1, -4, -4, 2};
    int nextIdx = getNextIdx(3, test);    
} 

Example: If the current index is 3 (4th element), and the value of the 4th element in the array is -4, and the size of the array is 6, then the function should return 5.

The problem is that my program returns 3 in the above example.


Solution

  • The modulus operator rounds towards zero (even for negative numbers). Your math expects modulus to round towards negative or positive infinity. See Modulo operation with negative numbers

    int getNextIdx(int currentIdx, vector<int> array){
      int jump = array[currentIdx];
      int nextIdx = currentIdx + jump;
      if (nextIdx < 0)
        nextIdx += array.size();
      if (nextIdx >= array.size())
        nextIdx -= array.size();
      return nextIdx;
    }