Created
February 15, 2012 17:27
-
-
Save Muon/1837465 to your computer and use it in GitHub Desktop.
Levenshtein algorithm implementation 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 = (a, b) -> | |
# Handle degenerate cases | |
if a == b | |
return 0 | |
unless a.length > 0 and b.length > 0 | |
return a.length or b.length | |
# Normalize order for cache | |
if b.length < a.length | |
[a, b] = [b, a] | |
unless levenshtein.cache[a]? | |
levenshtein.cache[a] = {} | |
if levenshtein.cache[a][b]? | |
return levenshtein.cache[a][b] | |
# Levenshtein only needs the current and previous rows of the matrix | |
prevRow = [0..a.length] | |
curRow = [0] | |
for j in [1..b.length] | |
curRow = [j] | |
for i in [1..a.length] | |
if a[i - 1] == b[j - 1] | |
curRow[i] = prevRow[i - 1] | |
else | |
curRow[i] = Math.min(curRow[i - 1], prevRow[i], prevRow[i - 1]) + 1 | |
prevRow = curRow | |
levenshtein.cache[a][b] = curRow[a.length] | |
levenshtein.cache = {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment