1

I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the 4th way of doing it (again - without using "if" blocks at all).

It feels like I need to use bit operation but I'm not dominant in this area so I need help.

Any ideas?

Thanks!

ClimbingLung
  • 219
  • 2
  • 8

4 Answers4

8
int fun(int p)
{
    return p^2;
}
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
5

As well as the obvious bitwise XOR solution, you can also exploit the fact that a boolean expression returns 1 or 0, e.g.

int f(int x)
{
    return (x == 5) * 7 + (x == 7) * 5;
}

and there are other simple arithmetic methods, e.g.

int f(int x)
{
    return 12 - x;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 1
    The first one is still some kind of "if" BUT I really like the 12-X. Simple, clean and straightforward. I should have tought about it :=) – ClimbingLung Mar 12 '14 at 12:32
  • The first one is actually branchless in general - try compiling it and look at the generated code. – Paul R Mar 12 '14 at 12:49
3

I hope this is no homework I do for you:

int mysteriousFunction( int x ) {
    return (x ^ 2);
}
Flovdis
  • 2,945
  • 26
  • 49
  • It's OK - this is not homework, just a challange to give different solutions to one problem and to think in different ways – ClimbingLung Mar 12 '14 at 12:33
0

if input range is bounded and small, use input as index into a lookup table of results...

Leo smith
  • 106
  • 4