How can I get permutations of a list?

前端 未结 5 2023
梦如初夏
梦如初夏 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:33

    There's a slightly different approach, it also supports specifing the desired length for the result lists:

    defmodule Permutations do
      def shuffle(list), do: shuffle(list, length(list))
    
      def shuffle([], _), do: [[]]
      def shuffle(_,  0), do: [[]]
      def shuffle(list, i) do
        for x <- list, y <- shuffle(list, i-1), do: [x|y]
      end
    end
    

    Running:

    iex(24)> Permutations.shuffle ["a", "b", "c"]
    [["a", "a", "a"], ["a", "a", "b"], ["a", "a", "c"], ["a", "b", "a"],
     ["a", "b", "b"], ["a", "b", "c"], ["a", "c", "a"], ["a", "c", "b"],
     ["a", "c", "c"], ["b", "a", "a"], ["b", "a", "b"], ["b", "a", "c"],
     ["b", "b", "a"], ["b", "b", "b"], ["b", "b", "c"], ["b", "c", "a"],
     ["b", "c", "b"], ["b", "c", "c"], ["c", "a", "a"], ["c", "a", "b"],
     ["c", "a", "c"], ["c", "b", "a"], ["c", "b", "b"], ["c", "b", "c"],
     ["c", "c", "a"], ["c", "c", "b"], ["c", "c", "c"]]
    
    iex(25)> Permutations.shuffle ["a", "b", "c"], 2
    [["a", "a"], ["a", "b"], ["a", "c"], ["b", "a"], ["b", "b"], ["b", "c"],
     ["c", "a"], ["c", "b"], ["c", "c"]]
    

    Source

提交回复
热议问题