gpt4 book ai didi

arrays - 在ruby中获取多级数组的组合

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:32 25 4
gpt4 key购买 nike

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]

值(value)观本身是独一无二的。

提前致谢!

最佳答案

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

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"]
# ]

希望对您有所帮助。

关于arrays - 在ruby中获取多级数组的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com