Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrementing a value and wrapping back to a max value without using if statement?

Incrementing and wrapping back to zero is easy:

i = (i + 1) % Max;

But decrementing is not as straight forward. Basically to decrement and wrap you usually find code like this:

i--;
if (i < 0)
   i = Max;

How can we write the previous code without using if statements?

I know that probably bit-wise operators will be involved. Usually when I'm faced with such problems I try to come up with some equations with two terms A and B, then try to find the actual values of these two terms. For example:

i = A + B

if i was in the range ]0, Max] then we'd get:

i = 0 + B and B = i-1

otherwise if i == 0:

i = A + 0 and A = Max

similarly we can write:

i = i == 0 ? Max : i - 1;

How to write the previous equation without any ifs or ternary operators? I tried so many bit-wise operations and different arithmetic combos but to no avail.

Any ideas?

like image 946
vexe Avatar asked Nov 02 '25 18:11

vexe


1 Answers

i = (Max-1 + i)%Max

will work as long as 0<=i<Max.

like image 112
David Munro Avatar answered Nov 04 '25 11:11

David Munro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!