Skip to content

Instantly share code, notes, and snippets.

@Kenny2github
Last active June 9, 2022 04:19
Show Gist options
  • Save Kenny2github/5f205d92bfc25682f7551d6d4b88dc79 to your computer and use it in GitHub Desktop.
Save Kenny2github/5f205d92bfc25682f7551d6d4b88dc79 to your computer and use it in GitHub Desktop.
Implementation of combinations and permutations in Elixir
defmodule Combinatorics do
def combinations(_, 0), do: [[]]
def combinations([], _), do: []
def combinations([head | rest], n) do
(for item <- combinations(rest, n - 1), do: [head | item]) ++ combinations(rest, n)
end
def permutations([]), do: [[]]
def permutations(list) do
for h <- list, t <- permutations(list -- [h]), do: [h | t]
end
def permutations(list, n) do
list |> combinations(n) |> Enum.map(&permutations/1) |> Enum.concat()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment