Created
March 23, 2023 21:30
-
-
Save domhnall/b2209e1e27abc2a2b2e5e24e32fe7ac6 to your computer and use it in GitHub Desktop.
Small script demonstrating how we can generate combinations from arrays of arrays
This file contains hidden or 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
def pretty_print(array_of_arrays) | |
array_of_arrays.each do |array| | |
puts "[#{array.join(",")}]" | |
end | |
end | |
def combinations_for_free(array_of_arrays) | |
array_of_arrays[0].product(*array_of_arrays[1...]) | |
end | |
def combinations(array_of_arrays) | |
array_of_arrays.reverse.reduce([[]]) do |solutions, arr| | |
cross_product(arr, solutions) | |
end | |
end | |
def cross_product(arr, array_of_arrays) | |
products = [] | |
arr.each do |elem| | |
array_of_arrays.map do |array| | |
products.push(array.clone.unshift(elem)) | |
end | |
end | |
products | |
end | |
# Let's test it ... | |
require 'minitest/autorun' | |
require 'debug' | |
class CombinationsTest < Minitest::Test | |
def cases | |
[ | |
[[0,1],[2,3],[4,5]], | |
[[1,2,3],[5],[6]], | |
[[0,1,2],[3,4],[5,6,7]] | |
] | |
end | |
def test_combinations | |
cases.each do |test_case| | |
assert combinations(test_case).sort == test_case[0].product(*test_case[1..]).sort | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment