2

Let's say I have the following input array of arrays:

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

I'd like to produce all permutations like this:

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

What's a nice Ruby way of doing this? Or really any way of doing this? I feel like there's an elegant solution that I can't see.

1 Answer 1

7

What you need is the cartesian product. Something like:

[1].product([2,3],[4,5],[6]) # => [[1, 2, 4, 6], [1, 2, 5, 6], [1, 3, 4, 6], [1, 3, 5, 6]]

Sign up to request clarification or add additional context in comments.

2 Comments

So how does one generalize this? Let's say my initial array is arr... is this arr[0].product(arr[1..-1]) or something? (It's not, I've tried it :))
Almost - you need to splat the arguments to product, as in arr[0].product(*arr[1..-1])

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.