In the last post we saw how to write a combinations
function. So, in this
post, we will see how to write a permutations
function in elixir, again
using pattern-matching and recursion:
defmodule Permutations do
@doc """
This function lists all permutations of all elements from the given `list`
"""
def permutations([]), do: [[]]
def permutations(list) do
for head <- list, tail <- permutations(list -- [head]), do: [head | tail]
end
end
## Examples
iex> Permutations.permutations([:a, :b, :c, :d])
[
[:a, :b, :c, :d],
[:a, :b, :d, :c],
[:a, :c, :b, :d],
[:a, :c, :d, :b],
[:a, :d, :b, :c],
[:a, :d, :c, :b],
[:b, :a, :c, :d],
[:b, :a, :d, :c],
[:b, :c, :a, :d],
[:b, :c, :d, :a],
[:b, :d, :a, :c],
[:b, :d, :c, :a],
[:c, :a, :b, :d],
[:c, :a, :d, :b],
[:c, :b, :a, :d],
[:c, :b, :d, :a],
[:c, :d, :a, :b],
[:c, :d, :b, :a],
[:d, :a, :b, :c],
[:d, :a, :c, :b],
[:d, :b, :a, :c],
[:d, :b, :c, :a],
[:d, :c, :a, :b],
[:d, :c, :b, :a]
]
iex> Permutations.permutations([1, 2, 3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]