Longest common prefix: Difference between revisions

Content added Content deleted
(Add CLU)
(Replace Ruby version with Elixir)
Line 1,371: Line 1,371:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>
{{trans|Ruby}}
<lang elixir>defmodule RC do
defmodule LCP 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("#{inspect(strs)} -> #{inspect(lcpstr(strs))}")
end)
end
end
end


defp lcpstr([]), do: ""
data = [
defp lcpstr(strs) do
["interspecies","interstellar","interstate"],
strs |> Enum.map(&String.to_charlist/1) |> lcp() |> IO.chardata_to_string()
["throne","throne"],
end
["throne","dungeon"],

["throne","","throne"],
defp 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 ->
</lang>
IO.puts "lcp(#{inspect strs}) = #{inspect RC.lcp(strs)}"
end)</lang>


{{out}}
{{out}}
<pre>
<pre>
lcp(["interspecies", "interstellar", "interstate"]) = "inters"
["interspecies", "interstellar", "interstate"] -> "inters"
lcp(["throne", "throne"]) = "throne"
["throne", "throne"] -> "throne"
lcp(["throne", "dungeon"]) = ""
["throne", "dungeon"] -> ""
lcp(["throne", "", "throne"]) = ""
["throne", "", "throne"] -> ""
lcp(["cheese"]) = "cheese"
["cheese"] -> "cheese"
lcp([""]) = ""
[""] -> ""
lcp([]) = ""
[] -> ""
lcp(["prefix", "suffix"]) = ""
["prefix", "suffix"] -> ""
lcp(["foo", "foobar"]) = "foo"
["foo", "foobar"] -> "foo"
</pre>
</pre>