Skip to content

Instantly share code, notes, and snippets.

@nbyouri
Last active August 11, 2017 08:39
Show Gist options
  • Save nbyouri/daf6e0ed64a238d09a74bf81eb352743 to your computer and use it in GitHub Desktop.
Save nbyouri/daf6e0ed64a238d09a74bf81eb352743 to your computer and use it in GitHub Desktop.
Tool to calculate edit-distance (levenshtein number) of two strings
# Compute the edit-distance of two strings, also called the Levenstein number.
function lev(x, y)
# edit-distance array
xl = length(x) + 1
yl = length(y) + 1
m = zeros(Int, xl, yl)
# init first line and column
for i = 1 : yl
m[1, i] = i - 1
end
for i = 1 : xl
m[i, 1] = i - 1
end
# update the values
for i = 2 : xl
for j = 2 : yl
# top left
m[i, j] = min(m[i - 1, j - 1] + ((x[i - 1] == y[j - 1]) ? 0 : 1),
# left or above
m[i, j - 1] + 1, m[i - 1, j] + 1)
end
end
return m#m[xl, yl]
end
# print matrix as latex array
function tolatex(m)
for i = 1 : size(m, 1)
for j = 1 : size(m, 2)
print(m[i,j]," & ")
end
print("\\\\","\n")
end
end
𝓫 = lev("iguane", "signaux")
𝛰 = lev("ADAND", "DNADNAA")
ϕ = lev("paradis", "paris")
tolatex(𝓫)
print("\n\n")
tolatex(𝛰)
print("\n\n")
tolatex(ϕ)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment