How can I get permutations of a list?

前端 未结 5 2017
梦如初夏
梦如初夏 2020-12-10 04:55

How can I get permutations of a list in Elixir?

Eg, for [\"a\", \"b\", \"c\"], I would expect:

# [[\"a\", \"b\", \"c\"], [\"a\", \"c\",          


        
5条回答
  •  抹茶落季
    2020-12-10 05:49

    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
    

提交回复
热议问题