I actually have to implement a string comparaison where I get a matching percentage at the end (not just boolean result match/unmatch). So, to do that I've found the Levenstein Distance algorithm. But the issue is now on performance. For instance, I have 1k strings to compare to each other, it takes about 10 minutes now. For each I already call the algo in parallel and again within each it's done in parallel. So i got in pseudo language :
Foreach strings
Call in parallel the comparaison method.
Within the comparaison method
Foreach stringsToCompare
Call in parallel the Levenstein Distance algo.
And still 10minutes at 100% CPU usage on a i5 @ 2.6Ghz...
Here's my implementation
public static double GetSimilarity(string firstString, string secondString)
{
if (ReferenceEquals(firstString, null)) throw new ArgumentNullException("firstString");
if (ReferenceEquals(secondString, null)) throw new ArgumentNullException("secondString");
if (firstString == secondString) return 100;
return (1 - GetLevensteinDistance(firstString, secondString) / (double)Math.Max(firstString.Length, secondString.Length)) * 100;
}
private static int GetLevensteinDistance(string firstString, string secondString)
{
if (ReferenceEquals(firstString, null)) throw new ArgumentNullException("firstString");
if (ReferenceEquals(secondString, null)) throw new ArgumentNullException("secondString");
if (firstString == secondString) return 1;
int[,] matrix = new int[firstString.Length + 1, secondString.Length + 1];
for (int i = 0; i <= firstString.Length; i++)
matrix[i, 0] = i; // deletion
for (int j = 0; j <= secondString.Length; j++)
matrix[0, j] = j; // insertion
for (int i = 0; i < firstString.Length; i++)
for (int j = 0; j < secondString.Length; j++)
if (firstString[i] == secondString[j])
matrix[i + 1, j + 1] = matrix[i, j];
else
{
matrix[i + 1, j + 1] = Math.Min(matrix[i, j + 1] + 1, matrix[i + 1, j] + 1); //deletion or insertion
matrix[i + 1, j + 1] = Math.Min(matrix[i + 1, j + 1], matrix[i, j] + 1); //substitution
}
return matrix[firstString.Length, secondString.Length];
}
So do you know a similar algo which is perhaps more appropriate for long text comparison or highly parallelizable ?