2

Currently I can get all permutations of a two item array as such:

[[:a, :b], [:c, :d]].reduce(&:product)
# => [[:a, :c], [:a, :d], [:b, :c], [:b, :d]]

However when I try and do the same for a three item array I do not get the desired result:

[[:a, :b], [:c, :d], [:e, :f]].reduce(&:product)
# => [[[:a, :c], :e], [[:a, :c], :f], [[:a, :d], :e], [[:a, :d], :f]]

The expected result is:

[[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f] ...]

2 Answers 2

2
data = [[:a, :b], [:c, :d], [:e, :f]]
data[0].product(*data[1..-1])
# => [[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f], [:b, :c, :e], [:b, :c, :f], [:b, :d, :e], [:b, :d, :f]]

and you can extend your data with more arrays

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

1 Comment

Or if your data is not stuck in one large array: a1.product(a2, a3, ...)
0

Since each item, such as [[:a, :c], :e] is almost correct it can be flattened:

[[:a, :b], [:c, :d], [:e, :f]].reduce(&:product).map(&:flatten)
# => [[:a, :c, :e], [:a, :c, :f], [:a, :d, :e], [:a, :d, :f] ...]

1 Comment

Absolutely genius

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.