开发者

Complex code/algorithm optimization (e.g. simplification) quandary

开发者 https://www.devze.com 2023-02-17 14:12 出处:网络
How can this code be simplified? if(x == 0) x = 1; else if (x == 1) x = 0; else if (x == 2) x = 3; 开发者_开发问答 else if (x == 3) x = 2;

How can this code be simplified?


  if      (x == 0) x = 1;
  else if (x == 1) x = 0;
  else if (x == 2) x = 3;
 开发者_开发问答 else if (x == 3) x = 2;


If x is always between 0 and 3 then try this:

x ^= 1;

It toggles the least significant bit.

If x can be a value other than between 0 to 3 then you can first test for that:

if (x >= 0 && x <= 3) {
    x ^= 1;
}


This is the simplest form possible:

if      (x == 0) x = 1;
else if (x == 1) x = 0;
else if (x == 2) x = 3;
else if (x == 3) x = 2;

wait... that's exactly your code.

cryptic one liners are NOT simple.


You could use something like this:

int mymap[4] = {1,0,3,2};

and then in your code use this:

x = mymap[x];


To use your pseudocode notation, maybe:

if (x % 2 == 0) x = x + 1
   else x = x - 1

e.g you are adding one if it is an even number, subtracting otherwise? In terms of optimization though, I don't see what is particularly slow or wrong with your original code.


if(x >= 0 && x <= 3)
  if((x%2) != 0) //odd
    x--;
  else if((x%2) == 0) //even
    x++;


Not that I think this is simpler, and it doesn't limit the case to 0..3, but:

x += (x % 2 == 0) ? 1 : -1; 


x ^= x & ~3 == 0 ? 1 : 0;

Unfortunately my code was so simplified it failed to make the 30-character minimum...


A common approach for handling simple data like this is to use the switch statement.


The code would be more redable with a switch statement:

switch(x) {
case 0: x=1: break;
case 1: x=0: break;
case 2: x=3: break;
case 3: x=2; break;
}

However, it's just about code readbility, not algorithmics, nor optimization.


x^=1;

unless x can be lower than 0 or higher than 3, which the problem specification doesn't state.


if( 0 <= x && x <= 3 )
  x ^= 1;


if ( x >>> 2 == 0 )
{   x ^= 1;
}


one liner:

x=(x==0)?1:((x==1)?0:(x==2)?3:(x==3)?2:x);


The best way to do this...

if(x % 2 == 0){
  x = +x;
}else{
  x = -x;
}


Probably using switch statements

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号