XOR of three values

前端 未结 8 926
执念已碎
执念已碎 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:38
    f= lambda{ |a| [false, false, true].permutation.to_a.uniq.include? a }
    p f.call([false, true, false])
    p f.call([false, true, true])
    

    $ true

    $ false

    Because I can.

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

    Here's a general implementation that fails quickly when more than one bool is found to be true.

    Usage:

    XOR(a, b, c);
    

    Code:

    public static bool XOR(params bool[] bools)
    {
        return bools.Where(b => b).AssertCount(1);
    }
    
    public static bool AssertCount<T>(this IEnumerable<T> source, int countToAssert)
    {
        int count = 0;
        foreach (var t in source)
        {
            if (++count > countToAssert) return false;
        }
    
        return count == countToAssert;
    }
    
    0 讨论(0)
提交回复
热议问题