Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to implement this very simple boolean logic using only math operands (such as mod)?

I want to decrease a value by one and if it reaches zero, set it to the maximum value. Is there a way to do this via math without resorting to if (n-1 == 0) { n = max; }

The opposite scenario of increasing a value by one and then setting it to zero when it is greater than max can easily be achieved using n = (n + 1) % (max + 1);. Furthermore, this is even better since you can increase by whatever amount (not just one) and it will still "wrap" correctly.

Thanks for the answers so far. To be clear, I meant without any boolean logic (if/else) or boolean operators (!, &&, etc) at all. I was just curious as to how to do this. Does the correct answer below really make it more unreadable as long as a comment is provided? It would be necessary to use that for the more general case for subtracting an arbitrary number and expecting the correct wrap around.

like image 337
GreenieMeanie Avatar asked Feb 17 '10 16:02

GreenieMeanie


2 Answers

n = max - ((max - n +1)%max)
like image 154
Ofir Avatar answered Nov 15 '22 05:11

Ofir


If you're doing this purely for performance reasons then I would advise against it. % is usually quite an expensive operation on most architectures - a simple comparison, branch and addition will usually be more efficient. Of course the usual caveats about speculative/premature optimisation apply.

like image 32
Paul R Avatar answered Nov 15 '22 05:11

Paul R