gpt4 book ai didi

ruby - 查找可变数量的 Ruby 数组的乘积

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:42 30 4
gpt4 key购买 nike

我希望从可变数量的数组中找到单个项目的所有组合。我如何在 Ruby 中执行此操作?

给定两个数组,我可以像这样使用 Array.product:

groups = []
groups[0] = ["hello", "goodbye"]
groups[1] = ["world", "everyone"]

combinations = groups[0].product(groups[1])

puts combinations.inspect
# [["hello", "world"], ["hello", "everyone"], ["goodbye", "world"], ["goodbye", "everyone"]]

当组包含可变数量的数组时,这段代码如何工作?

最佳答案

groups = [
%w[hello goodbye],
%w[world everyone],
%w[here there]
]

combinations = groups.first.product(*groups.drop(1))

p combinations
# [
# ["hello", "world", "here"],
# ["hello", "world", "there"],
# ["hello", "everyone", "here"],
# ["hello", "everyone", "there"],
# ["goodbye", "world", "here"],
# ["goodbye", "world", "there"],
# ["goodbye", "everyone", "here"],
# ["goodbye", "everyone", "there"]
# ]

关于ruby - 查找可变数量的 Ruby 数组的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3419952/

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