Skip to content

Instantly share code, notes, and snippets.

@sepastian
Last active January 11, 2023 09:26
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sepastian/6904643 to your computer and use it in GitHub Desktop.
Save sepastian/6904643 to your computer and use it in GitHub Desktop.
Build the cartesian product of multiple arrays in Ruby.
# Given an array of arrays s = [ [1,2,3], [4,5,6], ... ]
# compute the Cartesian product among the elements of s.
require 'pp'
s = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
pp s[1..-1].inject(s[0]){ |m,v| m = m.product(v).map(&:flatten) }
[[1, 3, 6],
[1, 3, 7],
[1, 3, 8],
[1, 3, 9],
[1, 4, 6],
[1, 4, 7],
[1, 4, 8],
[1, 4, 9],
[1, 5, 6],
[1, 5, 7],
[1, 5, 8],
[1, 5, 9],
[2, 3, 6],
[2, 3, 7],
[2, 3, 8],
[2, 3, 9],
[2, 4, 6],
[2, 4, 7],
[2, 4, 8],
[2, 4, 9],
[2, 5, 6],
[2, 5, 7],
[2, 5, 8],
[2, 5, 9]]
# Or, much simpler (RTFM):
s[0].product(*s[1..-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment