0

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)

2 Answers2

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

joriki
  • 238,052
  • 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
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$$

Berci
  • 90,745