Created
July 3, 2011 06:38
-
-
Save alecbz/1062009 to your computer and use it in GitHub Desktop.
ruby function for Levenshtein word distance
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
def distance(a,b) | |
matrix = Array.new(a.size + 1) { Array.new(b.size + 1) } | |
(0..a.size).each { |i| matrix[i][0] = i } | |
(0..b.size).each { |j| matrix[0][j] = j } | |
(1..a.size).each do |i| | |
(1..b.size).each do |j| | |
if a[i-1] == b[j-1] | |
matrix[i][j] = matrix[i-1][j-1] | |
else | |
matrix[i][j] = [matrix[i-1][j] + 1,matrix[i][j-1] + 1,matrix[i-1][j-1] + 1].min | |
end | |
end | |
end | |
matrix[a.size][b.size] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment