如何在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)
有一种略有不同的方法,它还支持为结果列表指定所需的长度:
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)
| 归档时间: |
|
| 查看次数: |
1965 次 |
| 最近记录: |