Skip to content

Instantly share code, notes, and snippets.

@tokafish
Created August 10, 2015 17:32
Show Gist options
  • Save tokafish/52e829f4cd9cdd0899f4 to your computer and use it in GitHub Desktop.
Save tokafish/52e829f4cd9cdd0899f4 to your computer and use it in GitHub Desktop.
defmodule CombinationsBenchmark do
def combinations(collection, k) do
List.last(do_combinations(collection, k))
end
defp do_combinations(list, k) do
combinations_by_length = [[[]]|List.duplicate([], k)]
List.foldr list, combinations_by_length, fn x, next ->
sub = :lists.droplast(next)
step = [[]|(for l <- sub, do: (for s <- l, do: [x|s]))]
:lists.zipwith(&:lists.append/2, step, next)
end
end
def combinations2(_, 0), do: [[]]
def combinations2([], _), do: []
def combinations2([h|t], k) do
(for l <- combinations2(t, k - 1), do: [h|l]) ++ combinations2(t, k)
end
end
list = Enum.to_list(1..50)
{ fast, _ } = :timer.tc(fn ->
for k <- 1..6 do
CombinationsBenchmark.combinations(list, k)
end
end, [])
IO.puts "CombinationsBenchmark.combinations completed in #{fast}"
{ slow, _ } = :timer.tc(fn ->
for k <- 1..6 do
CombinationsBenchmark.combinations2(list, k)
end
end, [])
IO.puts "CombinationsBenchmark.combinations2 completed in #{slow}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment