【问题标题】:Finding the product of a variable number of Ruby arrays查找可变数量的 Ruby 数组的乘积
【发布时间】:2011-03-26 02:22:43
【问题描述】:

我希望从可变数量的数组中找到单个项目的所有组合。我如何在 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"]]

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

【问题讨论】:

    标签: ruby loops product depth


    【解决方案1】:
    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"]
    # ]
    

    【讨论】:

    • 哇,谢谢。您或其他人能否解释一下这是如何工作的?
    • 解释这实际上做了什么也会有帮助,并且可能会导致更好地设计 OP 的代码......
    • @Ollie: Array#product 可以接受多个数组作为参数,所以这基本上就是在做groups[0].product(groups[1],groups[2],...)
    • 它是如何工作的:product 接受你应用的许多数组,并给出接收器的笛卡尔积和所有参数。 splat 运算符将一个数组“扩展”为一个参数列表,因此我们将groups 中除第一个以外的所有数组作为参数传递给product
    • 请注意,如果您的groups 数组是真正可变的,则必须考虑它何时为空且只有1 个数组,否则您可能会得到undefined method 'product' for nil:NilClass
    猜你喜欢
    • 2011-04-14
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多