0
$\begingroup$

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)

  • 0
    Yes 1-b would have been simpler, cycling would be the correct term, apologies2012-10-19

2 Answers 2

2

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\;. $

  • 0
    @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.2012-10-21
0

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

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

  • 0
    thanks very helpful - I did try and make the question answered - not sure if I succeeded?2012-10-21