(a==b) ? a : c;
boolean
atLeastTwo(
boolean
a,
boolean
b,
boolean
c) {
if
((a && b) || (b && c) || (a && c)) {
return
true
;
}
else
{
return
false
;
}
}
Then the interviewer asked him to improve the solution given and make it more concise. He didn't know how to improve the solution, so he posted the question on StackOverflow. There are some people who gave very useful solutions. I think this is deserved to be discussed here for us to better understand boolean values and expressions in programming. Here I share some of these solutions with you.
Some one says if you have some code snippet like
if
(someExpression) {
return
true
;
}
else
{
return
false
;
}
You should modify it as
return
someExpression;
So the solution can be improved as
return
((a && b) || (b && c) || (a && c));
Of course there are some other excellent solutions. Such as Tim Stone gave the solution
return a ^ b ? c : a
Personally I think this solution is the most concise one.Also if we use Karnaugh map, we can have
return
a ? (b || c) : (b && c);
If we can treat bool values a 1 or 0, then we have a&b | b&c | c&a
a + b + c >= 2
If we cannot treat bool values as 1 or 0, then we have
int
howManyBooleansAreTrue =
(a ? 1 : 0)
+ (b ? 1 : 0)
+ (c ? 1 : 0);
return
howManyBooleansAreTrue >= 2;
Here is one more brilliant answer
Author : Source : http://coolshell.cn/articles/2514.html Original source : http://stackoverflow.com/questions/3076078/check-if-at-least-2-out-of-3-booleans-is-true/