如何获得列表的排列?

Nat*_*ong 9 elixir

如何在Elixir中获得列表的排列?

例如,["a", "b", "c"]我希望:

# [["a", "b", "c"], ["a", "c", "b"], 
# ["b", "a", "c"], ["b", "c", "a"],
# ["c", "a", "b"], ["c", "b", "a"]]
Run Code Online (Sandbox Code Playgroud)

Nat*_*ong 10

像这样:

defmodule Permutations do
  def of([]) do
    [[]]
  end

  def of(list) do
    for h <- list, t <- of(list -- [h]), do: [h | t]
  end
end
Run Code Online (Sandbox Code Playgroud)

  • @OnorioCatenacci这不是一个非常翔实的评论.:D我还不是Elixir专家.如果你有时间发帖,我会很高兴看到一个更惯用的解决方案 - 大多数时候我把它放在这里,因为我认为这是一个常见问题,但我没有找到答案.下次我搜索,我会.我认为它是其他人也可以使用的"自我注意". (5认同)
  • 评论并不是真的针对你。它更多地针对可能会看到您的代码的其他人,并且没有更好的了解,认为这是编写 Elixir 代码的正确方法。 (2认同)

sob*_*evn 5

有一种略有不同的方法,它还支持为结果列表指定所需的长度:

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
Run Code Online (Sandbox Code Playgroud)

运行:

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"]]
Run Code Online (Sandbox Code Playgroud)

资源

  • 我不确定这是否是所需的输出,有重复 (3认同)