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

It is easy to "switch" between 0 and 1 as follows:

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

Similarly, I found that you can “switch” between 3 and 5:

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

While this seems cumbersome, I'm looking for a more concise way to do this. Can this be simplified? If so, how? By the way, I use this for something.

+4
source share
5 answers

Much shorter:

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

And of course, for your 0/1 switch, you have to do this:

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

In general, to switch a / b do the following:

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

How it works? Well, a + b - a - b , and a + b - b - a .: - D

+12
source

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 
+9
source

You can say:

 i = 3; i = (i == 5) ? 3 : 5; // it five now i = (i == 5) ? 3 : 5; // it three now i = (i == 5) ? 3 : 5; // it five again 
+3
source

Also much shorter:

 i = 3; i ^= 6; // now i = 5 i ^= 6; // now i = 3 

To switch between the two numbers a and b , you need a constant value a XOR b - which is 1 for your first example and 6 per second.

+1
source

Or perhaps it’s more universal to use a function to map from consecutive integers to any repeating sequence of integers:

 #include <stdio.h> int mapModIntToSequence (int i, int mod, int x[]) { return x[i%mod]; } int main () { int i; int x[] = {2,7}; for (i = 0; i < 10; i++) { printf ("%d\n",mapModIntToSequence(i,2,x)); } } 

This approach has the bonus that it also works for sequences of any length, and not just for switching between two integers.

0
source

Source: https://habr.com/ru/post/1498529/


All Articles