Last active
August 29, 2015 14:10
-
-
Save davepeck/3590b2b584487175c127 to your computer and use it in GitHub Desktop.
Levenshtein Distance in coffeescript
This file contains 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
# Levenshtein distance with the ability to reward or punish | |
# longer contiguous matching runs (set contiguousBonus < 1.0 for rewards) | |
stringDistance = (s, t, deleteCost=1, insertCost=1, substitutionCost=1, contiguousBonus=1.0) -> | |
sLength = s.length | |
tLength = t.length | |
d = [] | |
for i in [0..sLength] | |
d[i] = [{score: i, contiguous: 0}] | |
for j in [0..tLength] | |
d[0][j] = {score: j, contiguous: 0} | |
for j in [1..tLength] | |
for i in [1..sLength] | |
if s.charAt(i-1) is t.charAt(j-1) | |
# Identical is zero cost | |
d[i][j] = {score: d[i-1][j-1].score, contiguous: d[i-1][j-1].contiguous + 1} | |
else | |
deletion = d[i-1][j].score + (deleteCost * Math.pow(contiguousBonus, d[i-1][j].contiguous)) | |
insertion = d[i][j-1].score + (insertCost * Math.pow(contiguousBonus, d[i][j-1].contiguous)) | |
substitution = d[i-1][j-1].score + (substitutionCost * Math.pow(contiguousBonus, d[i-1][j-1].contiguous)) | |
minScore = Math.min(deletion, insertion, substitution) | |
d[i][j] = {score: minScore, contiguous: 0} | |
return d[sLength][tLength].score |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment