Skip to content

Instantly share code, notes, and snippets.

View andrewlynch's full-sized avatar

Andrew Lynch andrewlynch

View GitHub Profile
@sepastian
sepastian / multi_cartesian_product.rb
Last active July 26, 2024 19:46
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],