Skip to content

Instantly share code, notes, and snippets.

@JuanitoFatas
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JuanitoFatas/a4c7e2d98fde193c712c to your computer and use it in GitHub Desktop.
Save JuanitoFatas/a4c7e2d98fde193c712c to your computer and use it in GitHub Desktop.
Levenshtein Distance in Ruby using matrix
# 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