Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Programming =>  Algorithm

A boolean value interview question

  陈皓      2012-04-30 08:49:32      3,984    0    0

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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

When PM says we can meet the deadline

By sonic0002