Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if exactly two out of three booleans are true?

I need to test to see if exactly two out of three booleans are true.

Something like this:

if ((a && b && !c) || (a && !b && c) || (!a && b && c)) {
  // success
}

Is this the most direct way to go about this? Does anyone know of a shortcut/shorthand?

like image 299
WillD Avatar asked Dec 21 '18 22:12

WillD


People also ask

Can you use == for Booleans?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".

How do you know if a boolean value is true?

To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!

Can you compare two Booleans?

We use the compare() method of the BooleanUtils class to compare two boolean values. The method takes two values and returns true if both the values are the same. Otherwise, it returns false .

How do you know if two boolean values are equal?

boolean isEqual = Boolean. equals(bool1, bool2); which should return false if they are not equal, or true if they are.


3 Answers

To check if exactly two are equal to true:

[a, b, c].filter(Boolean).length === 2;

References:

  • Array.prototype.filter().
  • Boolean().
like image 137
David Thomas Avatar answered Oct 09 '22 19:10

David Thomas


If you add the values you can check if the result is 2

if ((a + b + c) == 2) {
    // do something
}
like image 6
ave4496 Avatar answered Oct 09 '22 19:10

ave4496


I would go this readable (IMO) way:

let conditions = [a && b && !c, a && !b && c, !a && b && c]
if(conditions.filter(c => c).length === 2) { /* ... */}
like image 1
Nurbol Alpysbayev Avatar answered Oct 09 '22 17:10

Nurbol Alpysbayev