Explain Codes LogoExplain Codes Logo

Check if at least two out of three booleans are true

java
bitwise-operations
boolean-logic
java-optimization
Nikita BarsukovbyNikita Barsukov·Nov 3, 2024
TLDR

If you're looking for a quick-and-dirty way to find out if at least two out of three boolean values a, b, c are true, here's the magic line:

boolean atLeastTwoTrue = (a && b) || (a && c) || (b && c);

This one-liner employs the powers of logical AND && and OR || operators to squash a potentially complex check into an easy, clean, and efficient statement.

Go bitwise: fast and furious in Java world

Unleash your bits

Bit-wise operators can give you a surprising turbo-boost. Here is how you can use them:

// When you live your life a quarter mile at a time, bitwise operations might just be your NOS. Fast and furious! boolean atLeastTwoTrue = a & b | b & c | c & a;

Sum-it-up technique

Or if you are an arithmetic enthusiast, you can convert the boolean to ints and sum them up:

// It's elementary, my dear Watson! int sum = (a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0); boolean atLeastTwoTrue = sum >= 2;

Shorthand strategies: when some tern around, others XOR-cise

Ternary is the new binary

If you like shortcuts (who doesn't?), you can make good use of ternary operators:

// Less is More boolean atLeastTwoTrue = a ? b || c : b && c;

XOR operation: the tiebreaker

Useful when two booleans are mutually exclusive and you can determine the outcome with XOR:

// Let the XOR decide the fate! boolean atLeastTwoTrue = a ^ b ? c : a;

Cut the fat, keep the meat: Efficient code

Simplify to amplify

Karnaugh Maps or truth tables can help you produce an optimal expression that's both efficient and readable.

Adapt and overcome

Depending on whether you're writing for a Java Server or Client Virtual Machine, you might want to modify your operations for performance.

Testing: because being sure never hurt anyone

Environment check

Make sure to test your solution in diverse environments to ensure its consistency.

Beneficial checks

Use truth tables and unit tests for comprehensive verification of your logic over all possible states.