# toggle boolean and more

Recently I used this to toggle a Boolean value, b being the current value and self.status being the result

self.status = (b-1)*(b-1)


This rather than use an if statement

How could I use the same concept to toggle more than 2 values? (ie -1 0 1)

-
This seems to be a programming problem, not a mathematics problem. – Michael Greinecker Oct 19 '12 at 10:32
It's not clear what "toggling" means for more than two values -- do you want to cycle through them? Using which operations? (Also note that 1-b would have been simpler for two values.) – joriki Oct 19 '12 at 10:38
Yes 1-b would have been simpler, cycling would be the correct term, apologies – peterretief Oct 19 '12 at 11:27

You can cycle through the numbers $0,\dotsc,n-1$ by adding $1$ and taking the remainder modulo $n$:

$$k\to(k+1)\bmod n\;.$$

Most programming languages have an operator for taking the remainder; in C-like syntax this would be k=(k+1)%n.

If you want to cycle through $a,\dotsc,b$ instead, just shift by $a$ before and after the operation:

$$k\to((k - a+ 1)\bmod (b-a+1))+a\;.$$

In your case, with $a=-1$ and $b=1$, this would be

$$k\to((k +2)\bmod 3)-1\;.$$

-
thanks very helpful - I did try and make the question answered - not sure if I succeeded? – peterretief Oct 21 '12 at 18:31
@peterretief: You're welcome. I'm not sure what you mean. If you mean you tried to keep it from being listed as unanswered: Yes, you succeeded; you accepted my answer and the question is therefore now considered resolved. – joriki Oct 21 '12 at 18:37
I accepted your answer and its resolved for me :) – peterretief Oct 22 '12 at 8:17

For 'toggling' $-1,0,1$ use $$x\mapsto -x$$

In general, for $a,a+1,a+2,..,b$, use $$x\mapsto (a+b)-x$$

-
thanks very helpful - I did try and make the question answered - not sure if I succeeded? – peterretief Oct 21 '12 at 18:25