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.
n = max - ((max - n +1)%max)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With