Created
September 19, 2012 07:45
-
-
Save wangshijun/3748245 to your computer and use it in GitHub Desktop.
javascript: calculation Levenshtein distance using dynamic programming
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 minimum(a,b,c) { | |
| var min = a; | |
| if (b<min) { | |
| min = b; | |
| } | |
| if (c<min) { | |
| min = c; | |
| } | |
| return min; | |
| } | |
| function levenshtein_distance(string1, string2) { | |
| length1 = string1.length; | |
| length2 = string2.length; | |
| if (length1 == 0) { | |
| return length2; | |
| } | |
| if (length2 == 0) { | |
| return length1; | |
| } | |
| var d = []; | |
| for(var i=0; i<=length1; i++) { | |
| d[i] = []; | |
| } | |
| for(var i=0; i<=length1; i++) { | |
| d[i][0] = i; | |
| } | |
| for(var j=0; j<=length2; j++) { | |
| d[0][j] = j; | |
| } | |
| for(var i=1; i<=length1; i++) { | |
| s_i = string1.charAt(i-1); | |
| for(var j=1; j<=length2; j++) { | |
| t_j = string2.charAt(j-1); | |
| if (s_i == t_j) { | |
| cost = 0; | |
| }else{ | |
| cost = 1; | |
| } | |
| d[i][j] = minimum(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost); | |
| } | |
| } | |
| for(var i=1; i<=length1; i++) { | |
| dG[i] = []; | |
| for(var j=1; j<=length2; j++) { | |
| dG[i][j] = d[i][j]; | |
| } | |
| } | |
| return d[length1][length2]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment