Created
April 7, 2011 18:47
-
-
Save jstepien/908415 to your computer and use it in GitHub Desktop.
A recursive approach to the Cartesian product
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
👍