Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use XOR to detect if exactly one of multiple conditions is true?

E.g.,

if (bool1 ^ bool2 ^ bool3 ^ bool4)
{
    // Do whatever
}

It should execute only if exactly one of the conditions is met.

like image 554
Beta Bet Avatar asked Feb 25 '17 18:02

Beta Bet


2 Answers

Add the bools together as integers and check if they equal 1.

In a language where casting from a boolean to an integer doesn't work, such as Java, the more long winded option is:

if ((bool1 ? 1 : 0) + (bool2 ? 1 : 0) + (bool3 ? 1 : 0) + (bool4 ? 1 : 0) == 1) {
    // only runs when one of bool 1-4 is true
}

However, in other languages where casting a boolean to an integer is valid, you can do the following:

if ((int)(bool1) + (int)(bool2) + (int)(bool3) + (int)(bool4) == 1) {
    // only runs when one of bool 1-4 is true
}
like image 78
Liam Gray Avatar answered Oct 05 '22 11:10

Liam Gray


As an alternative, here is a stream-based solution:

boolean b0 = false;
boolean b1 = false;
boolean b2 = true;
boolean b3 = false;

boolean result = Stream.of(b0, b1, b2, b3)
    .mapToInt(b -> b ? 1 : 0)
    .sum() == 1;

System.out.println(result);

It has the advantage that it can easily be applied to 3 or 5 boolean values, or to generically implement a boolean exactlyOne(boolean ... b) method.

like image 26
Marco13 Avatar answered Oct 05 '22 12:10

Marco13