0

Say I'm incrementing or decrementing an index which I'll use to move through an array.

The array starts at index 0, and ends at index 4. If I'm at index 0 and want to move back 1 index, I should end up at index 4 (wraps around).

This is probably extremely simple, but for some reason I just can't come up with a formula that would give me this result. "wrap around addition" was pretty straight forward: index % 5 + 1, but I just can't figure out subtraction.

Mike729
  • 61
  • 4

2 Answers2

1

The correct formula for addition is (index + 1) % 5. Your version gives the wrong result when index is 4.

The correct formula for subtraction depends on the behaviour of the % operator in the language you're using:

  • In Python, (index - 1) % 5 is correct because % guarantees a result between 0 and 4 inclusive even when the left-hand-side is negative.
  • In C and Java, (index + 4) % 5 is correct, because % would return a negative remainder when the left-hand-side is negative. Note that this formula would also work in Python.

For more discussion see this other Q&A.

kaya3
  • 47,440
  • 4
  • 68
  • 97
0

Formula

newindex = (index + increment + arraylen) % arraylen

works for increments +1 and -1 (forward and backward moving).

arraylen = 5 in your example

MBo
  • 77,366
  • 5
  • 53
  • 86