Longest common prefix: Difference between revisions

Replace Scala with Erlang
(Replace Ruby version with Elixir)
(Replace Scala with Erlang)
Line 1,420:
 
=={{header|Erlang}}==
 
A bow to the perversion of the Scala implementation. Not canonical erlang, this.
 
{{trans|Scala}}
 
<lang erlang>
 
-module(lcp).
-export([ main/10 ]).
data() -> [
shortest(List,Size) when length(List) =:= 0 ->
[ ["interspecies", "interstellar", "interstate"],
Size;
["throne", "throne"],
["throne", "dungeon"],
["throne", "", "throne"],
["cheese"],
Size;[""],
if [],
["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.
 
uniqlcp(List, Size []) -> [];
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}}
<pre>
["interspecies","interstellar","interstate"] -> "inters"
6> Data =
["throne","throne"] -> "throne"
[["interspecies","interstellar","interstate"],
["throne","thronedungeon"], -> ""
["throne",[],"dungeonthrone"], -> ""
["thronecheese",[], -> "thronecheese"],
[[]] -> ""
["cheese"],
[] -> ""
[[]],
["prefix","suffix"] -> ""
[],
["prefixfoo","suffixfoobar"], -> "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>