开发者

Creating permutations from a multi-dimensional array in Ruby

I have the following multi-dimensional array in Ruby:

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

I need to have the following output:

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

I have trie开发者_开发问答d creating a recursive function, but I'm not having much luck.

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

Thanks


Yup, Array#product does just that (Cartesian 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]] 

Another variant:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜