How can I get permutations of a list in Elixir?
Eg, for [\"a\", \"b\", \"c\"]
, I would expect:
# [[\"a\", \"b\", \"c\"], [\"a\", \"c\",
Here's a version without comprehensions:
defmodule Permute do
def permute(_chars, building, 0) do
[building]
end
def permute(chars, building, dec) do
Stream.map(chars, fn char -> building ++ [char] end)
|> Enum.flat_map(fn building -> permute(chars, building, dec - 1) end)
end
end
Useful to have a helper function to allow the input as a string too:
def permute(str) do
permute(String.split(str, "", trim: true), [], String.length(str))
end