Created
May 12, 2009 14:00
-
-
Save javascripter/110495 to your computer and use it in GitHub Desktop.
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
# >http://d.hatena.ne.jp/kenkitii/20090204/ruby_levenshtein_distance> | |
def levenshtein_distance(str1, str2) | |
col, row = str1.size + 1, str2.size + 1 | |
d = row.times.inject([]){|a, i| a << [0] * col } | |
col.times {|i| d[0][i] = i } | |
row.times {|i| d[i][0] = i } | |
str1.size.times do |i1| | |
str2.size.times do |i2| | |
cost = str1[i1] == str2[i2] ? 0 : 1 | |
x, y = i1 + 1, i2 + 1 | |
d[y][x] = [d[y][x-1]+1, d[y-1][x]+1, d[y-1][x-1]+cost].min | |
end | |
end | |
d[str2.size][str1.size] | |
end | |
# << | |
def method_missing(name, *args) | |
s = methods.min_by {|s| levenshtein_distance name.to_s, s } | |
puts "Did you mean this? #{s}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment