Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating permutations from a multi-dimensional array in Ruby

Tags:

arrays

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 tried 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

like image 757
Trevor Avatar asked Apr 07 '11 14:04

Trevor


1 Answers

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]] 
like image 189
Mladen Jablanović Avatar answered Sep 28 '22 05:09

Mladen Jablanović