在ruby中获得多级数组的组合

时间:2015-05-13 11:42:26

标签: arrays ruby combinations

a = [1,2,3,4].combination(3).to_a

返回

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

我需要做些什么来获得下面显示的数组的以下组合

[["1a","1b"],2,3,4]

应该是

=> [["1a", 2, 3], ["1a", 2, 4], ["1a", 3, 4],["1b", 2, 3], ["1b", 2, 4], ["1b", 3, 4], [2, 3, 4]]

重要的是,第二级的值不是组合在一起。

阵列也可以是

[["1a","1b","1c",...],2,3,4]

价值观本身是独一无二的。

提前致谢!

2 个答案:

答案 0 :(得分:3)

下面的解决方案将展平并生成阵列和标量的任意组合:

a = [["1a","1b"],2,3,["4a","4b"]]

a.combination(a.size - 1).map do |e| 
  e.map { |scalar| [*scalar] } # convert scalars to arrays of size 1
end.map do |arrays| 
  arrays.reduce &:product      # reduce by vector/cartesian product
end.flat_map do |deeps| 
  deeps.map &:flatten          # flatten the result
end

#⇒ [
#      ["1a", 2, 3], ["1b", 2, 3], ["1a", 2, "4a"], ["1a", 2, "4b"],
#      ["1b", 2, "4a"], ["1b", 2, "4b"], ["1a", 3, "4a"], 
#      ["1a", 3, "4b"], ["1b", 3, "4a"], ["1b", 3, "4b"],
#      [2, 3, "4a"], [2, 3, "4b"]
#  ]

希望它有所帮助。

答案 1 :(得分:2)

a = [["1a","1b"],2,3,4]

head, tail = [a[0], a[1..-1]]

res = head.flat_map{|h| ([h] + tail).combination(3).to_a}.uniq