XOR of three values

前端 未结 8 925
执念已碎
执念已碎 2020-12-02 23:04

What is the simplest way to do a three-way exclusive OR?

In other words, I have three values, and I want a statement that evaluates to true IFF only one of

相关标签:
8条回答
  • 2020-12-02 23:19
    bool result = (a?1:0)+(b?1:0)+(c?1:0) == 1;
    
    0 讨论(0)
  • 2020-12-02 23:21

    You could also try (in C):

    !!a + !!b + !!c == 1

    0 讨论(0)
  • 2020-12-02 23:21

    Better yet on Python:

    result = (1 if a else 0)+(1 if b else 0)+(1 if c else 0) == 1
    

    This can be used also on if statements!

    It saved my day for CLI mutually exclusive arguments through Click (everyone hates click)

    0 讨论(0)
  • 2020-12-02 23:27

    For exactly three terms, you can use this expression:

    (a ^ b ^ c) && !(a && b && c)
    

    The first part is true iff one or three of the terms are true. The second part of the expression ensures that not all three are true.

    Note that the above expression does NOT generalize to more terms. A more general solution is to actually count how many terms are true, so something like this:

    int trueCount =
       (a ? 1 : 0) +
       (b ? 1 : 0) +
       (c ? 1 : 0) +
       ... // more terms as necessary 
    
    return (trueCount == 1); // or some range check expression etc
    
    0 讨论(0)
  • 2020-12-02 23:29

    Another possibility:

    a ? !b && !c : b ^ c
    

    which happens to be 9 characters shorter than the accepted answer :)

    0 讨论(0)
  • 2020-12-02 23:33

    a^b^c is only 1 if an uneven number of variables is 1 (two '1' would cancel each other out). So you just need to check for the case "all three are 1":

    result = (a^b^c) && !(a&&b&&c)
    
    0 讨论(0)
提交回复
热议问题