【问题标题】:Permutations in ElixirElixir 中的排列
【发布时间】:2020-01-10 09:32:45
【问题描述】:

我正在努力在 Elixir 中创建一个集合的排列。

Permuate([1,2,3])
[[1, 2, 3], [1, 3, 2], [2, 3, 1], [2, 1, 3], [3, 2, 1], [3, 1, 2]]

但是,我提出的每次尝试都以一些类似的版本结束:

[[2, [3, [1]], [1, [3]]], [3, [2, [1]], [1, [2]]], [1, [2, [3]], [3, [2]]]]

[[[2, [[3, 1]]], [2, [[1, 3]]]], [[3, [[2, 1]]], [3, [[1, 2]]]],
[[1, [[2, 3]]], [1, [[3, 2]]]]]

几乎就在那里.. 只是需要一些关于使用 Elixir 构建列表的启示。

我的代码如下所示:

defmodule Permutations do
    def permutate_set(s) do
        if Set.size(s) == 1 do
            Set.to_list(s)
        else
            Enum.map(s, fn(a) ->
                Enum.map(permutate_set(Set.delete(s, a)), fn(b) ->
                    [a] ++ [b]
                end)
            end)
        end
    end
end

【问题讨论】:

标签: elixir


【解决方案1】:

注意:

查找所有权限:

defmodule Perms do
  def perms(%MapSet{} = set),
    do: MapSet.to_list(set) |> perms

  def perms([]), do: [[]]

  def perms(l) do
    for h <- l, t <- perms(l -- [h]),
      do: [h|t]
  end
end


defmodule PermsTest do
  use ExUnit.Case
  doctest Perms

  test "find perms from set" do
    assert [[1, 2], [2, 1]] == Perms.perms(MapSet.new([1,2]))
    assert [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] == Perms.perms(MapSet.new([1,2,3]))
  end

  test "find perms" do
    assert [[1, 2], [2, 1]] == Perms.perms([1,2])
    assert [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] == Perms.perms([1,2,3])
  end
end

【讨论】:

    【解决方案2】:

    我认为这里的问题是您的匿名函数中的变量b 已经是一个列表。通过将其包装在 [] 中,您将使其成为一个包含列表的列表。

    【讨论】:

    • 抱歉,我不是要挑剔 - 这个答案看起来更像是评论而不是答案。如果您愿意,您可以详细说明您的建议,并可能分享 OP 代码的更正版本或您的代码版本,以供未来读者使用
    • @WandMaker 我正在解决 OPs 代码中的具体问题。一般情况已经在上面链接的 Gazler 帖子中得到解答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多