在 Ruby 中从多维数组创建排列 [英] Creating permutations from a multi-dimensional array in Ruby

查看:22
本文介绍了在 Ruby 中从多维数组创建排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ruby 中有以下多维数组:

I have the following multi-dimensional array in Ruby:

[[1,2], [3], [4,5,6]]

我需要有以下输出:

[[1,3,4], [1,3,5], [1,3,6], [2,3,4], [2,3,5], [2,3,6]]

我尝试过创建递归函数,但运气不佳.

I have tried creating a recursive function, but I'm not having much luck.

是否有任何 Ruby 函数可以帮助解决此问题?或者是递归执行的唯一选择?

Are there any Ruby functions that would help with this? Or is the only option to do it recursively?

谢谢

推荐答案

是的,Array#product 就是这样做的(笛卡尔积):

a = [[1,2], [3], [4,5,6]]
head, *rest = a # head = [1,2], rest = [[3], [4,5,6]]
head.product(*rest)
#=> [[1, 3, 4], [1, 3, 5], [1, 3, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6]] 

另一种变体:

a.inject(&:product).map(&:flatten)
#=> [[1, 3, 4], [1, 3, 5], [1, 3, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6]] 

这篇关于在 Ruby 中从多维数组创建排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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