Check if at least two out of three booleans are true
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:
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:
Sum-it-up technique
Or if you are an arithmetic enthusiast, you can convert the boolean to ints and sum them up:
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:
XOR operation: the tiebreaker
Useful when two booleans are mutually exclusive
and you can determine the outcome with XOR:
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.
Was this article helpful?