-10

For the sake of challenge, how can I replace this code with only one if statement?

unsigned int x, y;
cin>>x;
if((x>=0)&&(x<=1)) y = 1;
else if (x<=3) y = 2;
    else if(x<=5) y = 3;
        else y = 6;
Jan Hohenheim
  • 3,552
  • 2
  • 17
  • 42
Alexander
  • 11
  • 3

3 Answers3

2

Make a table of inputs and outputs:

0 — 1
1 — 1
2 — 2
3 — 2
4 — 3
5 — 3
Other — 6

Now make a logical expression which distinguishes specific inputs from "others".

x ≥ 0 and x ≤ 5

(note: for unsigned type you can remove the comparison with 0)

Now make a formula which calculates given outputs from given inputs:

x / 2 + 1
anatolyg
  • 26,506
  • 9
  • 60
  • 134
1

Without knowing why you want to use a single if, it's hard to tell. Of course, you can use ternary operators without any ifs:

unsigned int x, y;
cin>>x;
y = x<=1
? 1
: x<=3 
    ? 2
    : x<=5
      ? 3
      : 6;

Or ugly boolean casting hacks for exactly one if (please don't actually do this outside of a puzzle or codegolf context):

unsigned int x, y;
cin>>x;
if (x<=5) {
    y = 1 + (int)(x == 2 || x == 3) + (int)(x == 4 || x == 5);
} else {
    y = 6;
}

Or, if you insist on exactly one if:

unsigned int x, y;
cin>>x;
if (x <= 5) {
   y = x/2 + 1;
} else {
   y = 6;
}

@Pietrek's answer shows you the better variant with a ternary operator (slightly modified here):

unsigned int x, y;
cin>>x;
auto const cutoff = 6;
y = x < cutoff ? x/2 + 1 : cutoff;

Note that in any case x >= 0 is always true when working with unsigned data types, so I omitted it.


If this is not purely a puzzle challenge but actual production code, please use the last example and make the number 6 a const or constexpr with a meaningful name.

Jan Hohenheim
  • 3,552
  • 2
  • 17
  • 42
0
y = x <= 5 ? x / 2 + 1 : 6;
Pietrek
  • 66
  • 6