I want to return True
if and only if 3 out of 4 boolean values are true.
The closest I've gotten is (x ^ y) ^ (a ^ b)
:
What should I do?
I suggest writing the code in a manner that indicates what you mean. If you want 3 values to be true, it seems natural to me that the value 3 appears somewhere.
For instance, in C++
:
if ((int)a + (int)b + (int)c + (int)d == 3)
...
This is well defined in C++
: the standard (§4.7/4)
indicates that converting bool
to int
gives the expected values 0 or 1.
In Java and C#, you can use the following construct:
if ((a?1:0) + (b?1:0) + (c?1:0) + (d?1:0) == 3)
...