Created
August 26, 2010 19:15
-
-
Save ufm/552029 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
-module(levenshtein). | |
-export([distance/2]). | |
distance(Source, Source) -> 0; | |
distance(Source, []) -> length(Source); | |
distance([], Source) -> length(Source); | |
distance(Source, Target) -> | |
D1 = lists:seq(0, length(Target)), | |
outer_loop([[]|Source], [[]|Target], {D1, D1}, 1). | |
outer_loop([S1|[S0|S]], T, {D2, D1}, I) -> | |
D0 = inner_loop(T, [S1, S0], {[[]|D2], D1, [I]}), | |
outer_loop([S0|S], T, {D1, D0}, I + 1); | |
outer_loop([_S|[]], _, {_D1, D0}, _) -> | |
lists:last(D0). | |
inner_loop([_T|[]], _, {_D2, _D1, D0}) -> | |
lists:reverse(D0); | |
inner_loop([T1|[T0|T]], [S1, S0], {D2, D1, D0}) -> | |
[S1T1|[S1T0|_]] = D1, | |
Cost = if T0 =:= S0 -> 0; true -> 1 end, | |
NewDist1 = lists:min([hd(D0) + 1, S1T0 + 1, S1T1 + Cost]), | |
NewDist2 = | |
if T1 =/= [] andalso S1 =/= [] andalso T1 =:= S0 andalso T0 =:= S1 -> | |
lists:min([NewDist1, hd(D2) + Cost]); | |
true -> NewDist1 | |
end, | |
inner_loop([T0|T], [S1, S0], {tl(D2), tl(D1), [NewDist2|D0]}). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment