wrap-around
wrap-around copied to clipboard
Devise a more elegant formula for handling negative numbers
Currently using (n % m + m) % m which looks hideously overcomplicated. sure it passes tests, but there's gotta be a better way of doing it?
What's wrong with doing Math.abs(n % m)?
incidentally this is what i tried first; see this section of the readme - abs(n % m) yields incorrect output e.g. f(-4) -> 1 instead of 2
haha. 7 years later. here's mine: some magic numbers but it works:
((n + 1) % m) + m - 1
n % m
this provides numbers in the range [-m+1, 0].
((n) % m) + (m - 1)
adding (m-1) puts them in the expected range [0,m] AND in the expected order, but off by 1.
((n + 1) % m) + m - 1
replacing n with n + 1 accounts for the offset
Good thing 1 isn't a magic number 🙂 Sacrifices a bit of readability to get the order of ops right but I guess it is one less modulo. If you put a PR up I can patch it through