2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,28 +1,27 @@
defmodule RC do
# hash table approach
def uniq1(list) do
Enum.reduce(list, HashSet.new, fn x, set -> Set.put(set, x) end)
|> Set.to_list
end
# Set approach
def uniq1(list), do: MapSet.new(list) |> MapSet.to_list
# Sort approach
def uniq2(list), do: Enum.sort(list) |> uniq2([])
defp uniq2([], uniq), do: Enum.reverse(uniq)
defp uniq2([h|t], uniq) when h==hd(uniq), do: uniq2(t, uniq)
defp uniq2([h|t], uniq) , do: uniq2(t, [h | uniq])
def uniq2(list), do: Enum.sort(list) |> Enum.dedup
# Go through the list approach
def uniq3(list), do: uniq3(list, [])
defp uniq3([], uniq), do: Enum.reverse(uniq)
defp uniq3([h|t], uniq) do
if Enum.member?(uniq, h), do: uniq3(t, uniq), else: uniq3(t, [h | uniq])
defp uniq3([], res), do: Enum.reverse(res)
defp uniq3([h|t], res) do
if h in res, do: uniq3(t, res), else: uniq3(t, [h | res])
end
end
list = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']
IO.inspect Enum.uniq(list)
IO.inspect RC.uniq1(list)
IO.inspect RC.uniq2(list)
IO.inspect RC.uniq3(list)
num = 10000
max = div(num, 10)
list = for _ <- 1..num, do: :rand.uniform(max)
funs = [&Enum.uniq/1, &RC.uniq1/1, &RC.uniq2/1, &RC.uniq3/1]
Enum.each(funs, fn fun ->
result = fun.([1,1,2,1,'redundant',1.0,[1,2,3],[1,2,3],'redundant',1.0])
:timer.tc(fn ->
Enum.each(1..100, fn _ -> fun.(list) end)
end)
|> fn{t,_} -> IO.puts "#{inspect fun}:\t#{t/1000000}\t#{inspect result}" end.()
end)