Skip to content

Commit 4e6f959

Browse files
author
Ben Schmeckpeper
committed
Permutations
1 parent 64cc726 commit 4e6f959

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

permutations.exs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
defmodule Permutations do
2+
def of([]), do: [[]]
3+
def of(set) do
4+
Enum.flat_map(set, fn(x) ->
5+
subset = of(List.delete(set, x))
6+
Enum.map(subset, fn(p) -> [x | p] end)
7+
end)
8+
end
9+
end
10+
11+
ExUnit.start
12+
13+
defmodule PermutationTests do
14+
use ExUnit.Case, async: false
15+
16+
test "permutations of an empty list is an empty list" do
17+
assert Permutations.of([]) == [[]]
18+
end
19+
20+
test "permutations of a single item list is the item" do
21+
assert Permutations.of([1]) == [[1]]
22+
end
23+
24+
test "it computes permutations" do
25+
assert Permutations.of([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
26+
end
27+
end
28+
29+

0 commit comments

Comments
 (0)