The following code
System.out.println(\"1 0 0: \" + (true ^ false ^ false));
System.out.println(\"1 0 1: \" + (true ^ false ^ true));
System.out.println(\"1 1 0:
If you want a true result, if one and only one inputs is true you can use:
(a ^ b ^ c ) ^ ( a && b && c )
the test case result:
true true true = false
true true false = false
true false true = false
true false false = true
false true true = false
false true false = true
false false true = true
false false false = false
Think about how the compiler evaluates this:
(true ^ true) ^ true
After first term true ^ true
, which is false
, has been evaluated:
(false) ^ true ==> true
'^' is a binary logical operator, not an n-ary operator.
Because true xor true = false, and false xor true is true. xor is associative, so group the values any way you please!
To decide that only one of them is true, you could add the values together as integers and see if the answer is 1.
I'm answering this as a general programming question, it really isn't particular to Java.
true ^ true ^ true
can be written (for understanding) as ( true ^ true ) ^ true
which is true
.
If A, B, C are inputs, for the logic that you are looking for, you need something like this
(A & !B & !C) | (!A & B & !C) | (!A & !B & C)
I don't know is it discovered and highlighted, but I noticed a thing that if we add all values together (no matter how many are there) and see what's left after division by 2 we can notice the result is false
if 0
left and true
if 1
left.
Example:
1 ^ 0 ^ 1 ^ 1 = 1
and
(1+0+1+1)%2 = 1
They are the same. Please, correct or guide me who has a clue about this case.