Created
April 29, 2019 09:59
-
-
Save jaynetics/45847cb34ed1f39e164a2aa84be47047 to your computer and use it in GitHub Desktop.
subarray / 2d-array / cross-array combinations 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
# 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