在 ruby 中获取多级数组的组合
Getting combinations of multilevel arrays in ruby
a = [1,2,3,4].combination(3).to_a
returns
[[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]
值本身是唯一的。
提前致谢!
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
下面的解决方案将展开并生成数组和标量的任意组合:
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"]
# ]
希望对您有所帮助。
a = [1,2,3,4].combination(3).to_a
returns
[[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]
值本身是唯一的。
提前致谢!
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
下面的解决方案将展开并生成数组和标量的任意组合:
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"]
# ]
希望对您有所帮助。