Sunday, May 27, 2012

Check if at least 2 out of 3 booleans is true


An interviewer recently asked me this question: given 3 boolean variables a, b, c, return true if at least 2 out of the 3 are true.



My solution follows:




boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}else{
return false;
}
}



He said that this can be improved further, but I'm not sure how?


Source: Tips4all

2 comments:

  1. Rather than writing:

    if (someExpression) {
    return true;
    } else {
    return false;
    }


    Write:

    return someExpression;




    As for the expression itself, something like this:

    boolean atLeastTwo(boolean a, boolean b, boolean c) {
    return a ? (b || c) : (b && c);
    }


    or this (whichever you find easier to grasp):

    boolean atLeastTwo(boolean a, boolean b, boolean c) {
    return a && (b || c) || (b && c);
    }


    It tests a and b exactly once, and c at most once.

    References


    JLS 15.25 Conditional Operator ? :

    ReplyDelete
  2. Just for the sake of using XOR to answer a relatively straight-forward problem...

    return a ^ b ? c : a

    ReplyDelete