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/1 ]).
-export([ main/0 ]).
data() -> [
shortest(List,Size) when length(List) =:= 0 ->
["interspecies", "interstellar", "interstate"],
Size;
["throne", "throne"],
["throne", "dungeon"],
["throne", "", "throne"],
["cheese"],
[""],
[],
["prefix", "suffix"],
["foo", "foobar"]
].


main() -> [io:format("~p -> \"~s\"~n",[Strs,lcp(Strs)]) || Strs <- data()].
shortest(List,Size) ->
[H|T] = List,
if
length(H) < Size ->
shortest(T, length(H) );
true ->
shortest(T, Size )
end.


uniq(List, Size ) ->
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).
</lang>


</lang>
{{out}}
{{out}}
<pre>
<pre>
["interspecies","interstellar","interstate"] -> "inters"
6> Data =
["throne","throne"] -> "throne"
[["interspecies","interstellar","interstate"],
["throne","throne"],
["throne","dungeon"] -> ""
["throne","dungeon"],
["throne",[],"throne"] -> ""
["throne",[],"throne"],
["cheese"] -> "cheese"
[[]] -> ""
["cheese"],
[] -> ""
[[]],
["prefix","suffix"] -> ""
[],
["prefix","suffix"],
["foo","foobar"] -> "foo"
["foo","foobar"],
["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>