Last active
June 9, 2022 04:19
-
-
Save Kenny2github/5f205d92bfc25682f7551d6d4b88dc79 to your computer and use it in GitHub Desktop.
Implementation of combinations and permutations in Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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