Reputation: 9
int distance = s.ToCharArray()
.Zip(t.ToCharArray(), (c1, c2) => new { c1, c2 })
.Count(m => m.c1 != m.c2);
This code id to calculate the hamming distance but can't seem to understand how it does it (i'm a beginner in c# )
Upvotes: 0
Views: 98
Reputation: 13652
Given two strings of the same length, the Hamming distance is defined as the number of different characters at each position, e.g. best and test have distance 1. The code you provided uses the Zip
function to create a list of character pairs for each position (index) in the string. Lets go through the code one by one:
Assuming you have these two strings:
string s = "test";
string t = "best";
string.ToCharArray()
converts them to arrays of char
:
char[] sChars = ['t', 'e', 's', 't'];
char[] tChars = ['b', 'e', 's', 't'];
Then, sChars.Zip(tChars, (c1, c2) => new { c1, c2 })
applied on those, creates a list of char pairs (actually anonymous classes containing two chars
):
var zippedChars = [
{c1 = 't', c2 = 'b'},
{c1 = 'e', c2 = 'e'},
{c1 = 's', c2 = 's'},
{c1 = 't', c2 = 't'}
];
Then zippedChars.Count(m => m.c1 != m.c2)
counts where the first character from the pair is not equal to the other one:
var distance = 1;
Upvotes: 1