Skip to content

Instantly share code, notes, and snippets.

@sepastian
Last active July 26, 2024 19:46
Show Gist options
  • 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])
@jaredbeck
Copy link

jaredbeck commented Jul 26, 2024

A minor suggestion: In the long form, I think the assignment (m =) is unnecessary in an inject?

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