Trevor
Trevor

Reputation: 6689

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

Upvotes: 13

Views: 2358

Answers (1)

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

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

Upvotes: 34

Related Questions