Created
May 8, 2018 21:42
-
-
Save costaraphael/e9972e60c2b9ef1f25fb3f70acd992cc to your computer and use it in GitHub Desktop.
Calculating 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 Permutations do | |
def permutate([]), do: [[]] | |
def permutate(list) do | |
for n <- list, | |
p <- permutate(list -- [n]), | |
do: [n | p] | |
end | |
end |
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 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