Logic to test that 3 of 4 are True

Simon Kuang picture Simon Kuang · Mar 7, 2014 · Viewed 11.7k times · Source

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?

Answer

sam hocevar picture sam hocevar · Mar 7, 2014

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)
    ...