Longest common prefix: Difference between revisions
Content added Content deleted
(Replace Ruby version with Elixir) |
(Replace Scala with Erlang) |
||
Line 1,420: | Line 1,420: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
A bow to the perversion of the Scala implementation. Not canonical erlang, this. |
|||
{{trans|Scala}} |
|||
<lang erlang> |
<lang erlang> |
||
-module(lcp). |
-module(lcp). |
||
-export([ main/ |
-export([ main/0 ]). |
||
data() -> [ |
|||
shortest(List,Size) when length(List) =:= 0 -> |
|||
⚫ | |||
⚫ | |||
["throne", "throne"], |
|||
["throne", "dungeon"], |
|||
["throne", "", "throne"], |
|||
⚫ | |||
⚫ | |||
⚫ | |||
["prefix", "suffix"], |
|||
⚫ | |||
]. |
|||
main() -> [io:format("~p -> \"~s\"~n",[Strs,lcp(Strs)]) || Strs <- data()]. |
|||
shortest(List,Size) -> |
|||
[H|T] = List, |
|||
⚫ | |||
length(H) < Size -> |
|||
shortest(T, length(H) ); |
|||
true -> |
|||
shortest(T, Size ) |
|||
end. |
|||
lcp( []) -> []; |
|||
lcp([S|Strs]) -> lists:foldl( fun(X,Y) -> lcp(X,Y,[]) end, S, Strs). |
|||
First = string:substr(hd(List),1,Size), |
|||
Last = string:substr(lists:last(List),1,Size), |
|||
Ttuples = lists:zip(First, Last), |
|||
% this is the bit that is like the scala version |
|||
TheList = lists:takewhile( |
|||
fun(E) -> |
|||
case element(1,E) =:= element(2,E) of true -> true; |
|||
_ -> false |
|||
end |
|||
end, Ttuples), |
|||
Prefix = length(TheList), |
|||
io:format("Prefix: ~p~n", [string:substr(First,1,Prefix)]). |
|||
main(List) -> |
|||
Sorted = lists:sort(List), |
|||
if |
|||
length(List) < 2 -> |
|||
io:format("Prefix empty:$~p~n",[List]); |
|||
true -> |
|||
Size = length(hd(List)), |
|||
uniq(Sorted, shortest(Sorted,Size)) |
|||
end. |
|||
lcp([X | Xs], [X | Ys], Pre) -> lcp(Xs, Ys, [X|Pre]); |
|||
lcp(_, _, Pre) -> lists:reverse(Pre). |
|||
⚫ | |||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
["interspecies","interstellar","interstate"] -> "inters" |
|||
6> Data = |
|||
["throne","throne"] -> "throne" |
|||
⚫ | |||
["throne","dungeon"] -> "" |
|||
["throne",[],"throne"] -> "" |
|||
["cheese"] -> "cheese" |
|||
[[]] -> "" |
|||
⚫ | |||
[] -> "" |
|||
[[]], |
|||
["prefix","suffix"] -> "" |
|||
[], |
|||
["foo","foobar"] -> "foo" |
|||
⚫ | |||
["foreign","forsake","forget","forlorn","forgiven"]]. |
|||
7> [lcp:main(X) || X <- Data]. |
|||
Prefix: "inters" |
|||
Prefix: "throne" |
|||
Prefix: [] |
|||
Prefix: [] |
|||
Prefix empty:$["cheese"] |
|||
Prefix empty:$[[]] |
|||
Prefix empty:$[] |
|||
Prefix: [] |
|||
Prefix: "foo" |
|||
Prefix: "for" |
|||
[ok,ok,ok,ok,ok,ok,ok,ok,ok,ok] |
|||
</pre> |
</pre> |
||