Skip to content

Instantly share code, notes, and snippets.

@alecbz
Created July 3, 2011 06:38
Show Gist options
  • Save alecbz/1062009 to your computer and use it in GitHub Desktop.
Save alecbz/1062009 to your computer and use it in GitHub Desktop.
ruby function for Levenshtein word distance
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