Reversed direction modulo operator?

253 Views Asked by At

This: i = ((i + 1) % itemArray.length assigns to i the next space going towards the right in a circular manner.

Is there a way I can make i go in a circular manner, but towards the left?

2

There are 2 best solutions below

0
On BEST ANSWER

Yep; replace $(i+1)$ with $(i-1)$. IF your language has a screwy modulo operator for negative numbers, you might have to use

i = ((i + (itemArray.length - 1)) % itemArray.length

instead

0
On

It depends on the implementation of the % operator; if it’s implemented sensibly, you can simply replace $i+1$ by $i-1$. Check to see whether -1 % 5 returns $-1$ or $4$. If it returns $4$, you’re in good shape. Otherwise, replace $i+1$ by i - 1 + itemArray.length if you don’t want to consider separate cases.

Basically you want to hope that the implementation does not use truncated division as described here.