I want to reduce the value by one, and if it reaches zero, set it to the maximum value. Is there a way to do this using math without resorting to if (n-1 == 0) { n = max; } if (n-1 == 0) { n = max; }
The opposite scenario of increasing the value by one, and then setting it to zero when it is greater than max, can be easily achieved with n = (n + 1) % (max + 1); . In addition, it is even better, since you can increase any amount (not just one), and it will still βturn aroundβ correctly.
Thanks for the answers so far. To be clear, I meant without logical logic (if / else) or logical operators (!, & &, Etc.) in general. I was just curious how to do this. Does the correct answer actually make it more unreadable if a comment is provided? It would be necessary to use this for a more general case to subtract an arbitrary number and expect the correct wrapper.
language-agnostic math algorithm
Greeniemeanie
source share