59 lines
1.8 KiB
C#
59 lines
1.8 KiB
C#
using System;
|
|
|
|
namespace DeukBot4.Utilities
|
|
{
|
|
public class Lehvenstein
|
|
{
|
|
/// <summary>
|
|
/// Calculates the Levenshtein distance between two strings--the number of changes that need to be made for the first string to become the second.
|
|
/// </summary>
|
|
/// <param name="first">The first string, used as a source.</param>
|
|
/// <param name="second">The second string, used as a target.</param>
|
|
/// <returns>The number of changes that need to be made to convert the first string to the second.</returns>
|
|
/// <remarks>
|
|
/// From http://www.merriampark.com/ldcsharp.htm
|
|
/// </remarks>
|
|
public static int LevenshteinDistance(string first, string second)
|
|
{
|
|
if (first == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(first));
|
|
}
|
|
if (second == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(second));
|
|
}
|
|
|
|
int n = first.Length;
|
|
int m = second.Length;
|
|
var d = new int[n + 1, m + 1]; // matrix
|
|
|
|
if (n == 0) return m;
|
|
if (m == 0) return n;
|
|
|
|
for (int i = 0; i <= n; d[i, 0] = i++)
|
|
{
|
|
}
|
|
|
|
for (int j = 0; j <= m; d[0, j] = j++)
|
|
{
|
|
}
|
|
|
|
for (int i = 1; i <= n; i++)
|
|
{
|
|
|
|
for (int j = 1; j <= m; j++)
|
|
{
|
|
int 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];
|
|
}
|
|
}
|
|
} |