Skip to content

Instantly share code, notes, and snippets.

@costaraphael
Created May 8, 2018 21:42
Show Gist options
  • Save costaraphael/e9972e60c2b9ef1f25fb3f70acd992cc to your computer and use it in GitHub Desktop.
Save costaraphael/e9972e60c2b9ef1f25fb3f70acd992cc to your computer and use it in GitHub Desktop.
Calculating permutations in Elixir
defmodule Permutations do
def permutate([]), do: [[]]
def permutate(list) do
for n <- list,
p <- permutate(list -- [n]),
do: [n | p]
end
end
defmodule PermutationsTest do
use ExUnit.Case
test "permutates a list" do
assert Permutations.permutate([]) == [[]]
assert Permutations.permutate([1]) == [[1]]
assert Permutations.permutate([1, 2]) == [[1, 2], [2, 1]]
assert Permutations.permutate([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment