结合数组的数组所有可能的组合,只向前,在Ruby中 [英] Combine array of array into all possible combinations, forward only, in Ruby

查看:107
本文介绍了结合数组的数组所有可能的组合,只向前,在Ruby中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组的数组,像这样:

I have an array of arrays, like so:

[['1','2'],['a','b'],['x','y']]

我需要向前只有那些阵列组合成一个包含所有三组的所有可能组合的字符串。我见过很多的套所有可能的组合的例子以任何顺序,这不是我想要的。举例来说,我不希望任何在第一盘的元素来第二盘之后,或者在第三盘第一个来,或第二之前,依此类推。因此,对于上面的例子中,输出将是:

I need to combine those arrays into a string containing all possible combinations of all three sets, forward only. I have seen lots of examples of all possible combinations of the sets in any order, that is not what I want. For example, I do not want any of the elements in the first set to come after the second set, or any in the third set to come before the first, or second, and so on. So, for the above example, the output would be:

['1ax', '1ay', '1bx', '1by', '2ax', '2ay', '2bx', '2by']

阵列的每一组的数目,并且长度是动态的。

The number of arrays, and length of each set is dynamic.

是否有人知道如何在Ruby中解决这个问题?

Does anybody know how to solve this in Ruby?

推荐答案

联络你的<一个href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-product\"><$c$c>Array#product:

a = [['1','2'],['a','b'],['x','y']]
a.first.product(*a[1..-1]).map(&:join)

这篇关于结合数组的数组所有可能的组合,只向前,在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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