Last active
January 11, 2023 09:26
-
-
Save sepastian/6904643 to your computer and use it in GitHub Desktop.
Build the cartesian product of multiple arrays in Ruby.
This file contains 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
# 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