Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simplify my "equation" to switch between 3 and 5?

It is easy to "switch" between 0 and 1 in the following way:

 int i = 0;
 i = (++i) % 2; // i = 1
 i = (++i) % 2; // i = 0

Similarly, I found that it is possible to "switch" between 3 and 5:

 int i = 3;
 i = (((i * 2) - 1) % 3) + 3; // i = 5
 i = (((i * 2) - 1) % 3) + 3; // i = 3

Whereas this feels cumbersome, I am searching for a more concise way to do it. Can it be simplified? If so, how? I am actually using this for something, by the way.

like image 284
dejay Avatar asked Nov 29 '22 02:11

dejay


2 Answers

Much shorter:

int i = 3;
i = 8 - i;
i = 8 - i;

And of course, for your 0/1 toggle, you should do this:

int i = 0;
i = 1 - i;
i = 1 - i;

And in general, for an a/b toggle, do this:

int i = a;
i = (a + b) - i;
i = (a + b) - i;

How does that work? Well, a + b - a is b, and a + b - b is a. :-D

like image 87
Chris Jester-Young Avatar answered Dec 04 '22 12:12

Chris Jester-Young


Another way is to use XOR, because a ^ (a ^ b) == b and b ^ (a ^ b) == a:

int i = 3;
i ^= 3 ^ 5; // i == 5
i ^= 3 ^ 5; // i == 3
like image 20
1'' Avatar answered Dec 04 '22 11:12

1''