Skip to content

Instantly share code, notes, and snippets.

@MerlinTwi
Last active December 21, 2017 15:50
Show Gist options
  • Select an option

  • Save MerlinTwi/924ddff8c2968f82b471779cf4283678 to your computer and use it in GitHub Desktop.

Select an option

Save MerlinTwi/924ddff8c2968f82b471779cf4283678 to your computer and use it in GitHub Desktop.
/// <summary>
/// Number of changes needed to turn one string into another.
/// Taken from https://www.dotnetperls.com/levenshtein
/// </summary>
public static int LevenshteinDistanceTo(string s, string t)
{
int n = s.Length;
int m = t.Length;
if (n == 0) return m;
if (m == 0) return n;
int[,] d = new int[n + 1, m + 1];
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 = (t[j - 1] == s[i - 1]) ? 0 : 1;
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];
}
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string[]> test = new List<string[]> {
new string[]{"ant", "aunt"},
new string[]{"Sam", "Samantha"},
new string[]{"clozapine", "olanzapine"},
new string[]{"flomax", "volmax"},
new string[]{"toradol", "tramadol"},
new string[]{"kitten", "sitting"}
};
foreach (string[] a in test) {
int cost = Extensions.LevenshteinDistanceTo(a[0], a[1]);
Console.WriteLine("{0} -> {1} = {2}", a[0], a[1], cost);
}
}
// Output:
// ant -> aunt = 1
// Sam -> Samantha = 5
// clozapine -> olanzapine = 3
// flomax -> volmax = 3
// toradol -> tramadol = 3
// kitten -> sitting = 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment