Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A recursive approach to the Cartesian product
# irb(main):001:0> cartprod [[:a, :b], (1..3), [true, false]]
# => [[:a, 1, true], [:a, 1, false], [:a, 2, true], [:a, 2, false],
# [:a, 3, true], [:a, 3, false], [:b, 1, true], [:b, 1, false],
# [:b, 2, true], [:b, 2, false], [:b, 3, true], [:b, 3, false]]
def cartprod(colls)
if colls.empty?
[[]]
else
rest_cartprod = cartprod colls[1..-1]
colls[0].reduce [] do |all, x|
all + rest_cartprod.map { |tail| [x] + tail }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment