Skip to content

Instantly share code, notes, and snippets.

@jstepien
Created April 7, 2011 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstepien/908415 to your computer and use it in GitHub Desktop.
Save jstepien/908415 to your computer and use it in GitHub Desktop.
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
@harold
Copy link

harold commented Jan 16, 2024

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment