I’m trying to find a one-line formula to calculate the previous number in a sequence wrapping round when it gets to zero, thus keeping the number in the range 1 - 8. I’ve managed to do it when getting the next number but cannot fathom out a formula when subtracting without using a conditional.
I could use a ternary operator but I’d still prefer to do it without a conditional if possible. I can’t help but feel it is possible but my little brain is overheating.
okay, it took me a minute to understand what you’re asking.
It’s a arse-to-elbows mechanism, and I think there’s a better way of doing it, but my brain is failing me at the moment… $p = (($i+6)%8)+1
And for those that try to figure out how i came up with that:
“The desired range is the numbers 1 to 8, wrapping around”
“Modulo wraps things around, but it starts from 0.”
“Okay, so shift the range: 0 to 7. We can add 1 afterwards and get back to where we want to be.”
“Right. So that’s a Modulo 8.”
“Yup. And now we need to shift the array backwards.”
“But the modulo of negative numbers doesnt work that way.”
“Okay, so shift FORWARDS until the cycle lines up again in the way that you want.”
“… 6 steps. Adding 7 to a cycle would be the equivilant of subtracting 1, but we start from 1, so it’s actually adding 6.”
“$i plus 6, modulo 8, add 1.”
Oops! $tot should be 8, and in the snippet neither $n (next) or $p (previous) are used.
It’s part of a script to loop through a number of images (8 in the example). $i, $n and $p are the current, next and previous images, prefixed by ‘image’ or something similar.