代码之家  ›  专栏  ›  技术社区  ›  Kris

多数组的置换

  •  1
  • Kris  · 技术社区  · 7 年前

    目前我可以得到一个两项数组的所有排列:

    [[:a, :b], [:c, :d]].reduce(&:product)
    # => [[:a, :c], [:a, :d], [:b, :c], [:b, :d]]
    

    但是,当我尝试对三项数组执行相同的操作时,并没有得到所需的结果:

    [[:a, :b], [:c, :d], [:e, :f]].reduce(&:product)
    # => [[[:a, :c], :e], [[:a, :c], :f], [[:a, :d], :e], [[:a, :d], :f]]
    

    预期结果是:

    [[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f] ...]
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   fl00r    7 年前
    data = [[:a, :b], [:c, :d], [:e, :f]]
    data[0].product(*data[1..-1])
    # => [[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f], [:b, :c, :e], [:b, :c, :f], [:b, :d, :e], [:b, :d, :f]]
    

    你可以用更多的数组扩展你的数据

        2
  •  0
  •   Kris    7 年前

    因为每个项目,比如 [[:a, :c], :e] 几乎是正确的,它可以变平:

    [[:a, :b], [:c, :d], [:e, :f]].reduce(&:product).map(&:flatten)
    # => [[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f] ...]
    
    推荐文章