Skip to content

Instantly share code, notes, and snippets.

@willasaywhat
Created September 3, 2009 19:24
Show Gist options
  • Save willasaywhat/180481 to your computer and use it in GitHub Desktop.
Save willasaywhat/180481 to your computer and use it in GitHub Desktop.
Levenshtein distance algorithm in Ruby
class Distance
attr_accessor :s1, :s2
def initialize(str1,str2)
@s1 = str1
@s2 = str2
end
def lev_distance
m = @s1.length
n = @s2.length
d = Array.new(m+1) { Array.new(n+1) {0} }
for i in 0..m
d[i][0] = i
end
for j in 0..n
d[0][j] = j
end
for j in 1..n
for i in 1..m
if (@s1[i-1] == @s2[j-1]) then
cost = 0
else
cost = 1
end
d[i][j] = [d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost].min
end
end
return d[m][n]
end
end
s1 = "kitten"
s2 = "sitting"
puts "Edit Distance between #{s1} and #{s2} is: " + Distance.new(s1,s2).lev_distance.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment