以下のように C# で LevenshteinDistance アルゴリズムを実装しました。このコードは完全に実行されています。しかし、デバッグ目的で行列を出力したいのですが、Print ステートメントをどこに配置すればよいかを判断できません。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _Levenshtein_
{
class Program
{
public static void Print(int[,] data)
{
for (int i = 0; i < data.GetUpperBound(0); i++)
{
for (int j = 0; j < data.GetUpperBound(1); j++)
{
Console.Write(data[i, j] + " ");
}
}
Console.WriteLine();
}
public static int LevenshteinDistance(string source, string target)
{
if (String.IsNullOrEmpty(source))
{
if (String.IsNullOrEmpty(target)) return 0;
{
return target.Length;
}
}
if (String.IsNullOrEmpty(target)) return source.Length;
if (source.Length > target.Length)
{
var temp = target;
target = source;
source = temp;
}
var m = target.Length;
var n = source.Length;
var distance = new int[2, m + 1];
// Initialize the distance 'matrix'
for (var j = 1; j <= m; j++) distance[0, j] = j;
Console.Write(target + " ");
var currentRow = 0;
for (var i = 1; i <= n; ++i)
{
currentRow = i & 1;
distance[currentRow, 0] = i;
var previousRow = currentRow ^ 1;
Console.WriteLine(source[i-1] + " " );
for (var j = 1; j <= m; j++)
{
var cost = (target[j - 1] == source[i - 1] ? 0 : 1);
distance[currentRow, j] = Math.Min(Math.Min(distance[previousRow, j] + 1,distance[currentRow, j - 1] + 1),distance[previousRow, j - 1] + cost);
Print(distance);
}
Console.WriteLine();
}
return distance[currentRow, m];
}
static void Main(string[] args)
{
LevenshteinDistance("Sunday", "Saturday");
}
}
}