Skip to content

Instantly share code, notes, and snippets.

@domhnall
Created March 23, 2023 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domhnall/b2209e1e27abc2a2b2e5e24e32fe7ac6 to your computer and use it in GitHub Desktop.
Save domhnall/b2209e1e27abc2a2b2e5e24e32fe7ac6 to your computer and use it in GitHub Desktop.
Small script demonstrating how we can generate combinations from arrays of arrays
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