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

查看:33
本文介绍了将数组组合成所有可能的组合,仅向前,在 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?

推荐答案

了解您的Array#product:

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

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

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