views:

145

answers:

3

I've got a 1-based array of four items which I need to traverse. For a given index in the array, I need to work out the index of the next item, and the index of the previous item. This sounds simple but the array needs to wrap around. So when you are at the beginning of the array, the previous item is considered to be the last item. Likewise, if you are at the end of the array, the next item is considered to be the first item.

I realise this can be solved by using conditional statements, but I wondered if it was possible to do it using mathematical equations. I've got one that works nicely for the next item

NextItem = Modulus(CurrentItem, 4) + 1

(the modulus function returns the remainder of one number divided by another).

Has anyone got any ideas as to how I can work out the previous item?

+2  A: 

Since modulo always works better on 0-based ranges, you can turn it into one of these using CurrentItem - 1.

Then, with modulo 4, adding 3 is the same as subtracting 1 but has the advantage of never going negative (some modulo operators may not like negatives).

Then you once again add 1 to get back to a 1-based number.

This gives:

PrevItem = Modulus(CurrentItem - 1 + 3, 4) + 1

or, simplified:

PrevItem = Modulus(CurrentItem + 2, 4) + 1
paxdiablo
A: 

There are two things to understand, firstly, Modulus(-1,n) = n-1, and secondly Modulus() will work best with 0-based indexing. Combining those two gives:

NextItem = Modulus((CurrentItem-1)+1, NumberOfItems) + 1
PrevItem = Modulus((CurrentItem-1)-1, NumberOfItems) + 1

For the specific case of NumberOfItems = 4, Modulus(-2,4) = 2, which gives Pax's answer and may be necessary if your system's Modulus() doesn't support negative numbers, but is not as clear.

Tom
A: 

It might depends on the properties of your Modulus against negative values, but in Lua the following works:

for i = 1, 8 do
  local idxF = i % 4 + 1
  local idxB = (i - 2) % 4 + 1
  print(i .. " " .. idxF .. " " .. idxB)
end

Should be PreviousItem = Modulus(CurrentItem - 2, 4) + 1 in your unspecified language.

PhiLho