我想用一個簡單的尾遞歸來檢索列表列表的所有排列。該模塊是這樣的:elixir中的二維列表的排列
defmodule Permutations do
def of([], accumulator) do
accumulator
end
def of([head | tail], accumulator) do
for item <- head, do: of(tail, accumulator ++ [item])
end
end
我對這個天賦的樣子:
defmodule PermutationsSpec do
use ESpec
alias WaffleEventImporter.Permutations
describe "of/2" do
subject do: Permutations.of(list_list, [])
let :list_list, do: [[1,2,3],[1,2,3],[1,2,3]]
let :expected, do: [
[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3],[1,3,1],[1,3,2],[1,3,3],
[2,1,1],[2,1,2],[2,1,3],[2,2,1],[2,2,2],[2,2,3],[2,3,1],[2,3,2],[2,3,3],
[3,1,1],[3,1,2],[3,1,3],[3,2,1],[3,2,2],[3,2,3],[3,3,1],[3,3,2],[3,3,3],
]
it "returns all permutations for the 2 diensional array provided" do
expect(subject) |> to(eq expected)
end
end
end
不幸的是,當遞歸解開排列的陣列嵌套。該規範的結果是:
Expected `[[[[1, 1, 1], [1, 1, 2], [1, 1, 3]], [[1, 2, 1], [1, 2, 2],
[1, 2, 3]], [[1, 3, 1], [1, 3, 2], [1, 3, 3]]], [[[2, 1, 1], [2, 1, 2],
[2, 1, 3]], [[2, 2, 1], [2, 2, 2], [2, 2, 3]], [[2, 3, 1], [2, 3, 2],
[2, 3, 3]]], [[[3, 1, 1], [3, 1, 2], [3, 1, 3]], [[3, 2, 1], [3, 2, 2],
[3, 2, 3]], [[3, 3, 1], [3, 3, 2], [3, 3, 3]]]]` to equals (==)
`[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3],
[1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3],
[2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3],
[3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3],
[3, 3, 1], [3, 3, 2], [3, 3, 3]]`, but it doesn't.
我希望有關如何防止嵌套的任何提示。不幸的是,平整輸出也刪除了組合的一階分組。
請分享「進程」功能。 – mudasobwa