查找可变数量的Ruby数组的乘积 [英] Finding the product of a variable number of Ruby arrays

查看:70
本文介绍了查找可变数量的Ruby数组的乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从数量可变的数组中找到单个项目的所有组合.如何在Ruby中做到这一点?

I'm looking to find all combinations of single items from a variable number of arrays. How do I do this in Ruby?

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

Given two arrays, I can use Array.product like this:

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

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

How could this code work when groups contains a variable number of arrays?

推荐答案

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数组的乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆