13

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

1
  • 3
    You should always show the code you've tried, even when it didn't work. Sometimes the fix is a minor tweak. Other times you'll get alternate solutions. Always, we'll be able to tell whether you've actually tried something or are just fishing for answers. Commented Apr 7, 2011 at 14:21

1 Answer 1

34

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]] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.