Thursday, August 22, 2013

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

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.

No comments:

Post a Comment