Search code examples
c#puzzleequality

What is an elegant way to check if 3 variables are equal when any of them can be a wildcard?


Say I have 3 char variables, a, b and c.
Each one can be '0', which is a special case and means it matches every char.

So if a is '0', I only need to check if b == c.
I want to check if a == b == c, but found the implementation in C# goes chaotic and lengthy.

Is there any creative or pretty solution you can offer?

update

for performance driven, take Erik A. Brandstadmoen's approach. for simplicity, use M4N's apprach, also i did some modification: !(query.Any() && query.Distinct().Skip(1).Any())


Solution

  • Something like this should work for any number of char values:

    public class Comparer
    {
        public static bool AreEqualOrZero(params char[] values)
        {
            var firstNonZero = values.FirstOrDefault(x => x != '0');
            return values.All(x => x == firstNonZero || x == '0');
        }
    }
    

    Passes the following unit tests:

    [TestClass()]
    public class ComparerTest
    {
    
        [TestMethod()]
        public void Matches_With_Wildcard()
        {
            char[] values = {'0', '1', '1', '1'};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Matches_With_No_Wildcard()
        {
            char[] values = {'1', '1', '1', '1'};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Matches_With_Only_Wildcards()
        {
            char[] values = {'0', '0', '0'};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Matches_With_Zero_Length()
        {
            char[] values = {};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Matches_With_One_Element()
        {
            char[] values = {'9'};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Matches_With_One_Wildcard_And_Nothing_Else()
        {
            char[] values = {'0'};
            Assert.IsTrue(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Does_Not_Match_On_NonEqual_Sequence_No_Wildcard()
        {
            char[] values = {'1', '2', '1', '1'};
            Assert.IsFalse(Comparer.AreEqualOrZero(values));
        }
    
        [TestMethod()]
        public void Does_Not_Match_On_NonEqual_Sequence_With_Wildcard()
        {
            char[] values = {'1', '2', '1', '0'};
            Assert.IsFalse(Comparer.AreEqualOrZero(values));
        }
    }