Last active
August 29, 2015 14:03
-
-
Save JuanitoFatas/a4c7e2d98fde193c712c to your computer and use it in GitHub Desktop.
Levenshtein Distance in Ruby using matrix
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 | |
# implementation given at http://en.wikipedia.org/wiki/Levenshtein_distance | |
# This file is in the public domain. | |
require 'matrix' | |
def levenshtein_distance str1, str2 | |
str1_len = str1.size | |
str2_len = str2.size | |
width = str1_len + 1 | |
height = str2_len + 1 | |
d = Matrix.zero(height, width) | |
width.times { |i| d.send(:[]=, 0, i, i) } | |
height.times { |i| d.send(:[]=, i, 0, i) } | |
str1_len.times do |x| | |
str2_len.times do |y| | |
cost = str1[x] == str2[y] ? 0 : 1 | |
d.send(:[]=, (1+y), (1+x), [ | |
d[y, (1+x)] + 1, | |
d[(1+y), x] + 1, | |
d[y, x] + cost | |
].min) | |
end | |
end | |
return d[str2_len, str1_len] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment