Developing the previous and next index in an array

I have a 1 element array of four elements that I need to traverse. For a given index in the array, I need to determine the index of the next element and the index of the previous element. It sounds simple, but the array needs to be wrapped. Therefore, when you are at the beginning of the array, the previous element is considered the last one. Likewise, if you are at the end of an array, the next element is considered the first element.

I understand that this can be solved using conditional operators, but I wondered if it could be done using math equations. I have one that works well for the next item.

NextItem = Modulus(CurrentItem, 4) + 1

      

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

Does anyone have any ideas as to how I can handle the previous element?

0


source to share


3 answers


Since modulo always performs better on ranges of 0, you can turn them into one with CurrentItem - 1

.

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

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

This gives:



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

      

or, simplified:

PrevItem = Modulus(CurrentItem + 2, 4) + 1

      

+2


source


There are two things to understand, first Modulus(-1,n) = n-1

, and second, it Modulus()

will work better with indexing 0

. Combining the two gives:

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

      



For a specific case NumberOfItems = 4

, Modulus(-2,4) = 2

that Pax gives an answer and may be needed if your Modulus () system does not support negative numbers, but is not so clear.

0


source


It might depend on the properties of your module 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

      

Must be PreviousItem = Modulus(CurrentItem - 2, 4) + 1

in your unspecified language.

-1


source







All Articles