Use LINQ

Hamming
Hamming in C#
using System;
using System.Linq;

public static class Hamming
{
    public static int Distance(string strand1, string strand2)
    {
        if (strand1.Length != strand2.Length)
            throw new ArgumentException("Strands have different length");

        return strand1.Zip(strand2).Count(pair => pair.First != pair.Second);
    }
}

The first step is to check if both strings have the same length:

if (strand1.Length != strand2.Length)
    throw new ArgumentException("Strands have different length");

Once we've verified that, we can safely use LINQ's Zip() (extension) method to combine both strings:

strand1.Zip(strand2)

This call returns a sequence of (char, char) tuples, the first element being (strand1[0], strand2[0]), the second (strand1[1], strand2[1]), and so on.

We then use the Count() method overload that takes a predicate to only count the tuple pairs that have different chars (meaning: the zipped strings have different characters at that index):

Count(pair => pair.First != pair.Second)

And with that, we have quite concise code that correctly calculates the hamming distance!

11th Dec 2024 · Found it useful?