Last active
December 14, 2021 22:42
-
-
Save Tsugami/d21b300bf4ddc6c4c30ed40bfdff035e to your computer and use it in GitHub Desktop.
Levenshtein Distance in Elixir
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
defmodule LevenShteinDistance do | |
def compare_distance(str, ""), do: String.length(str) | |
def compare_distance("", str), do: String.length(str) | |
def compare_distance(str, str), do: 0 | |
def compare_distance(str1, str2) do | |
[first1, rest1] = pattern_str(str1) | |
[first2, rest2] = pattern_str(str2) | |
if first1 === first2 do | |
compare_distance(rest1, rest2) | |
else | |
result = [ | |
compare_distance(str1, rest2), | |
compare_distance(rest1, str2), | |
compare_distance(rest1, rest2) | |
] | |
1 + Enum.min(result) | |
end | |
end | |
defp pattern_str(str) when is_binary(str) do | |
<<head, tail::binary>> = str | |
[<<head>>, tail] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment