-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHammingDistanceStrategy.cs
39 lines (25 loc) · 1.14 KB
/
HammingDistanceStrategy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
namespace Gsemac.Text {
public class HammingDistanceStrategy :
IStringDistanceStrategy {
// Public members
public double ComputeDistance(string first, string second, bool normalizeResult = false) {
if (first is null)
throw new ArgumentNullException(nameof(first));
if (second is null)
throw new ArgumentNullException(nameof(second));
if (string.IsNullOrEmpty(first) && string.IsNullOrEmpty(second))
return 0;
// Hamming distance assumes that both strings are the same length.
// To allow for strings of different lengths, we'll consider any extraneous characters non-matching.
int difference = Math.Abs(first.Length - second.Length);
int maxLength = Math.Max(first.Length, second.Length);
for (int i = 0; i < Math.Min(first.Length, second.Length); ++i)
if (first[i] != second[i])
++difference;
return normalizeResult ?
difference / (double)maxLength :
difference;
}
}
}