I'm almost embarrased to ask this, because it's probably VERY obvious - but I can't see a way out of this neatly and suspect there is one.
I have a variable which I need to add/subtract values from - but I want to keep it within a range of values, looping around at either end - e.g.
Range is 0-3 so values are 0,1,2,3,0,1,2,3 - and this does that
x = (x + val) MOD 4
When val is negative, however, we should see 0,3,2,1,0,3,2,1 and the solution is FAR less elegant
x = (x + val) MOD 4
if (x < 0) x = 4 + x;
That works, but it's clunky and I can't help thinking there might be a 'one line' solution to this - but I'm damned if I can think of it? :)
prepares for embarrassment