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;
CodePudding user response:
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
CodePudding user response:
Without knowing why you want to use a single if
, it's hard to tell. Of course, you can use ternary operators without any if
s:
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 this is a mathematical context, simply use the following with no if
s:
unsigned int x, y;
cin>>x;
y = min(6, x/2 1);
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.
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 third example with min
and make the number 6
a const
or constexpr
with a meaningful name.
CodePudding user response:
y = x <= 5 ? x / 2 1 : 6;