Visit the hamming exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Use LINQ
LINQ
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!
Use a for-loop
for-loop
using System;
public static class Hamming
{
public static int Distance(string strand1, string strand2)
{
if (strand1.Length != strand2.Length)
throw new ArgumentException("Strands have different length");
var distance = 0;
for (var i = 0; i < strand1.Length; i++)
{
if (strand1[i] != strand2[i])
distance++;
}
return distance;
}
}
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 define a variable that will keep track of the hamming distance between the two strings:
var distance = 0;
We then use a for-loop to iterate over each index of the first (and second) string:
for (var i = 0; i < strand1.Length; i++)
We could equally well have used `i < strand2.Length`, as both strings are guaranteed to have the same length.
Within the loop, we can then use a simple if-statement to check if the two strings have different characters at the specified index, and if so, increment the distance by one:
if (strand1[i] != strand2[i])
distance++;
Finally, once each index has been checked, we return the hamming distance:
return distance;
Source: Exercism csharp/hamming