Last active
August 29, 2015 14:22
-
-
Save jalada/28fa2cfdfa31717b0f28 to your computer and use it in GitHub Desktop.
Create all permutations of an array of an array.
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
comb([[3], ['a', 'c', 'f'], [4,6], [5,9]]) | |
=> ["3a45", "3a49", "3a65", "3a69", "3c45", "3c49", "3c65", "3c69", "3f45", "3f49", "3f65", "3f69"] |
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 comb(arr) | |
head = arr[0] | |
if arr[1..-1].present? | |
results = [] | |
head.each{|x| | |
comb(arr[1..-1]).each{|s| | |
results << "#{x}#{s}" # Adjust concatentation to suit your types. | |
} | |
} | |
return results | |
else | |
head | |
end | |
end |
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
# Then I discovered Array#product. D'oh! | |
def comb(arr) | |
arr.first.product(*arr[1..-1]).map(&:join) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment