Skip to content

Instantly share code, notes, and snippets.

@jaynetics
Created April 29, 2019 09:59
Show Gist options
  • Save jaynetics/45847cb34ed1f39e164a2aa84be47047 to your computer and use it in GitHub Desktop.
Save jaynetics/45847cb34ed1f39e164a2aa84be47047 to your computer and use it in GitHub Desktop.
subarray / 2d-array / cross-array combinations in ruby
# subarray_combinations([['a', 'b'], [1, 2]])
# # => [['a', 1], ['a', 2], ['b', 1], ['b', 2]]
def subarray_combinations(array_of_arrays, index = 0)
return [] if index == array_of_arrays.size
subarray = array_of_arrays[index]
tails = subarray_combinations(array_of_arrays, index + 1)
if tails.empty?
subarray.map { |item| [item] }
else
subarray.each_with_object([]) do |item, paths|
tails.each { |tail| paths << [item, *tail] }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment