Longest common prefix: Difference between revisions

Replace Ruby version with Elixir
(Add CLU)
(Replace Ruby version with Elixir)
Line 1,371:
 
=={{header|Elixir}}==
<lang elixir>
{{trans|Ruby}}
<lang elixir>defmodule RCLCP do
@data [
def lcp([]), do: ""
["interspecies", "interstellar", "interstate"],
def lcp(strs) do
["throne", "throne"],
min = Enum.min(strs)
["throne", "dungeon"],
max = Enum.max(strs)
["throne", "", "throne"],
index = Enum.find_index(0..String.length(min), fn i -> String.at(min,i) != String.at(max,i) end)
["cheese"],
if index, do: String.slice(min, 0, index), else: min
[""],
[],
["prefix", "suffix"],
["foo", "foobar"]
]
 
def main do
Enum.each(@data, fn strs ->
IO.puts "lcp("#{inspect (strs})} =-> #{inspect RC.lcp(lcpstr(strs))}")
end)
end
end
 
defp lcpstr([]), do: ""
data = [
defdefp lcplcpstr(strs) do
["interspecies","interstellar","interstate"],
strs |> Enum.map(&String.to_charlist/1) |> lcp() |> IO.chardata_to_string()
["throne","throne"],
end
["throne","dungeon"],
 
["throne","","throne"],
defdefp lcp([]), do: ""[]
["cheese"],
defp lcp(strs), do: Enum.reduce(strs, &lcp/2)
[""],
 
[],
defp lcp(xs, ys), do: lcp(xs, ys, [])
["prefix","suffix"],
 
["foo","foobar"]
defp lcp([x | xs], [x | ys], pre), do: lcp(xs, ys, [x | pre])
]
defp lcp(_, _, pre), do: Enum.reverse(pre)
end
Enum.each(data, fn strs ->
end)</lang>
IO.puts "lcp(#{inspect strs}) = #{inspect RC.lcp(strs)}"
end)</lang>
 
{{out}}
<pre>
lcp(["interspecies", "interstellar", "interstate"]) =-> "inters"
lcp(["throne", "throne"]) =-> "throne"
lcp(["throne", "dungeon"]) =-> ""
lcp(["throne", "", "throne"]) =-> ""
lcp(["cheese"]) =-> "cheese"
lcp([""]) =-> ""
lcp([]) =-> ""
lcp(["prefix", "suffix"]) =-> ""
lcp(["foo", "foobar"]) =-> "foo"
</pre>