在 Ruby 中将数组的数组组合成所有可能的组合(仅向前)
我有一个数组数组,如下所示:
[['1','2'],['a','b'],['x','y']]
我需要将这些数组组合成一个字符串,其中包含所有三个集合的所有可能组合(仅向前)。我已经看到了很多以任何顺序组合所有可能组合的例子,这不是我想要的。例如,我不希望第一组中的任何元素出现在第二组之后,或者第三组中的任何元素出现在第一组或第二组之前,依此类推。因此,对于上面的示例,输出将是:
['1ax', '1ay', '1bx', '1by', '2ax', '2ay', '2bx', '2by']
数组的数量和每组的长度是动态的。
有人知道如何用 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.
Does anybody know how to solve this in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
了解您的
Array#product
:Know your
Array#product
:使用递归的、所谓的“动态编程”方法来解决:
在代码中:
您也可以反转逻辑,并且小心地您应该能够实现这个非-递归地。但递归的答案相当简单。 :)
Solved using a recursive, so-called "Dynamic Programming" approach:
In code:
You could also reverse the logic, and with care you should be able to implement this non-recursively. But the recursive answer is rather straightforward. :)
纯、还原产物:
Pure, reduce with product: