Created
March 26, 2015 03:40
-
-
Save q3yi/55e95d50d6357d4d3fcf to your computer and use it in GitHub Desktop.
Useful Algorithms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function levenshteinDistance(strA, strB) { | |
// Function to calculate levenshtein distance of two string | |
// Algorithm description: http://en.wikipedia.org/wiki/Levenshtein_distance | |
if (strA == strB) { return 0; } | |
if (!strA || !strB) { return strA.length || strB.length; } | |
var distance = [], lenA = strA.length, lenB = strB.length; | |
for (var i=0; i <= lenA; i++) { distance[i] = [i]; } | |
for (var j=0; j <= lenB; j++) { distance[0][j] = j;} | |
for (i=1; i <= lenA; i++) { | |
for (j=1; j <= lenB; j++) { | |
distance[i][j] = Math.min(distance[i-1][j] + 1, | |
distance[i][j-1] + 1, | |
distance[i-1][j-1] + (strA.charAt(i-1) === strB.charAt(j-1) ? 0 : 1)); | |
} | |
} | |
return distance[lenA][lenB]; | |
} | |
function strSimilarity(strA, strB) { | |
// Function to calculate similar percent use levenshtein distance | |
var str1 = strA || '', | |
str2 = strB || '', | |
maxLen = str1.length > str2.length ? str1.length : str2.length, | |
distance = levenshteinDistance(str1, str2); | |
return !distance ? 1 : ((maxLen - distance) / maxLen); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment