using System; namespace DeukBot4.Utilities { public static class Lehvenstein { /// /// Calculates the Levenshtein distance between two strings--the number of changes that need to be made for the first string to become the second. /// /// The first string, used as a source. /// The second string, used as a target. /// The number of changes that need to be made to convert the first string to the second. /// /// From http://www.merriampark.com/ldcsharp.htm /// public static int LevenshteinDistance(string first, string second) { if (first == null) { throw new ArgumentNullException(nameof(first)); } if (second == null) { throw new ArgumentNullException(nameof(second)); } var n = first.Length; var m = second.Length; var d = new int[n + 1, m + 1]; // matrix if (n == 0) return m; if (m == 0) return n; for (var i = 0; i <= n; d[i, 0] = i++) { } for (var j = 0; j <= m; d[0, j] = j++) { } for (var i = 1; i <= n; i++) { for (var j = 1; j <= m; j++) { var cost = (second.Substring(j - 1, 1) == first.Substring(i - 1, 1) ? 0 : 1); // cost d[i, j] = Math.Min( Math.Min( d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } return d[n, m]; } } }