A boolean value interview question

Summary

The article explores various concise solutions to a common interview question: determining if at least two of three boolean variables are true. While an initial approach might involve explicit if/else or a direct logical OR combination like (a && b) || (b && c) || (a && c), more elegant alternatives exist. Developers can leverage the ternary operator for brevity, such as a ^ b ? c : a or (a==b) ? a : c. Another effective method involves treating booleans as integers (0 or 1) to sum their values and check if a + b + c >= 2, showcasing diverse approaches to optimize boolean logic.

Someone asked a question on StackOverflow, he was asked an interview question. The question is : Given 3 boolean variables a, b, c, return true if at least 2 out of the 3 are true. He gave the solution as follows :
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;
(Shareded by danatel)

Here is one more brilliant answer
(a==b) ? a : c;
Want to try yourself? Put your answer here.

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/
RETURN EXPRESSION BOOL CONDITIONAL

  RELATED

  COMMENTS

0

No comment for this article.