开发者

Creating permutations from a multi-dimensional array in Ruby

开发者 https://www.devze.com 2023-02-22 14:54 出处:网络
I have the following multi-dimensional array in Ruby: [[1,2], [3], [4,5,6]] I need to have the following output:

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

精彩评论

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