Skip to content

Instantly share code, notes, and snippets.

@kflu
Created May 30, 2012 16:26
Show Gist options
  • Save kflu/2837425 to your computer and use it in GitHub Desktop.
Save kflu/2837425 to your computer and use it in GitHub Desktop.
Calculate the edit distance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using SimpleTest;
namespace EditDistance
{
class Program
{
static void Main(string[] args)
{
Test.Assert(new EditDistance("A", "B").solve(), 1);
Test.Assert(new EditDistance("abc", "abb").solve(), 1);
Test.Assert(new EditDistance("abcd", "bcde").solve(), 2);
Test.Assert(new EditDistance("a", "a").solve(), 0);
Test.Assert(new EditDistance("", "").solve(), 0);
}
}
class EditDistance
{
public int m, n;
public string A, B;
private int[,] table, trace;
public EditDistance(string A, string B)
{
this.A = A;
this.n = A.Length;
this.B = B;
this.m = B.Length;
this.table = new int[n + 1, m + 1];
this.trace = new int[n + 1, m + 1];
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < m + 1; j++)
{
table[i, j] = -1;
trace[i, j] = -1;
}
}
for (int i = 0; i < n+1; i++)
{
table[i, 0] = i;
trace[i, 0] = 1;
}
for (int j = 0; j < m+1; j++)
{
table[0, j] = j;
trace[0, j] = 0;
}
trace[0, 0] = -1;
}
private int D(int i, int j)
{
if (i == 0) return j;
if (j == 0) return i;
Debug.Assert(i != 0 && j != 0);
if (table[i, j] != -1) return table[i, j];
if (A[i - 1] == B[j - 1])
{
trace[i, j] = 2;
table[i, j] = D(i - 1, j - 1);
}
else
{
var minPair = new int[] { D(i, j - 1), D(i - 1, j), D(i - 1, j - 1) }.Zip(
Enumerable.Range(0, 3), (distance, index) => Tuple.Create(index, distance)).Aggregate(
(a1, a2) => a1.Item2 < a2.Item2 ? a1 : a2);
table[i, j] = minPair.Item2 + 1;
trace[i, j] = minPair.Item1;
}
return table[i, j];
}
public int solve()
{
int minDist = D(n, m);
// TODO: trace the solution
return minDist;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment