HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Check if at least two out of three booleans are true

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arecheckthreebooleansoutleasttruetwo

Problem

An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three 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 how?

Solution

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 ? :

Code Snippets

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

Context

Stack Overflow Q#3076078, score: 848

Revisions (0)

No revisions yet.