Created
September 13, 2011 17:08
-
-
Save dplummer/1214345 to your computer and use it in GitHub Desktop.
Permutations of a hash of arrays
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
# Input: | |
# choices = { | |
# 'color' => %w(blue red green), | |
# 'sizes' => %w(small medium large extra-large), | |
# 'style' => %w(tshirt longsleeve) | |
# } | |
# | |
# Output: | |
# [{"sizes"=>"small", "color"=>"blue", "style"=>"tshirt"}, | |
# {"sizes"=>"small", "color"=>"blue", "style"=>"longsleeve"}, | |
# {"sizes"=>"medium", "color"=>"blue", "style"=>"tshirt"}, | |
# {"sizes"=>"medium", "color"=>"blue", "style"=>"longsleeve"}, | |
# {"sizes"=>"large", "color"=>"blue", "style"=>"tshirt"}, | |
# {"sizes"=>"large", "color"=>"blue", "style"=>"longsleeve"}, | |
# {"sizes"=>"extra-large", "color"=>"blue", "style"=>"tshirt"}, | |
# {"sizes"=>"extra-large", "color"=>"blue", "style"=>"longsleeve"}, | |
# {"sizes"=>"small", "color"=>"red", "style"=>"tshirt"}, | |
# {"sizes"=>"small", "color"=>"red", "style"=>"longsleeve"}, | |
# {"sizes"=>"medium", "color"=>"red", "style"=>"tshirt"}, | |
# {"sizes"=>"medium", "color"=>"red", "style"=>"longsleeve"}, | |
# {"sizes"=>"large", "color"=>"red", "style"=>"tshirt"}, | |
# {"sizes"=>"large", "color"=>"red", "style"=>"longsleeve"}, | |
# {"sizes"=>"extra-large", "color"=>"red", "style"=>"tshirt"}, | |
# {"sizes"=>"extra-large", "color"=>"red", "style"=>"longsleeve"}, | |
# {"sizes"=>"small", "color"=>"green", "style"=>"tshirt"}, | |
# {"sizes"=>"small", "color"=>"green", "style"=>"longsleeve"}, | |
# {"sizes"=>"medium", "color"=>"green", "style"=>"tshirt"}, | |
# {"sizes"=>"medium", "color"=>"green", "style"=>"longsleeve"}, | |
# {"sizes"=>"large", "color"=>"green", "style"=>"tshirt"}, | |
# {"sizes"=>"large", "color"=>"green", "style"=>"longsleeve"}, | |
# {"sizes"=>"extra-large", "color"=>"green", "style"=>"tshirt"}, | |
# {"sizes"=>"extra-large", "color"=>"green", "style"=>"longsleeve"}] | |
class Hash | |
def permutations_of_arrays | |
recursive_permute_arrays([], 0, {}, sort, count) | |
end | |
private | |
def recursive_permute_arrays(acc, choices_index, chosen, self_sort, self_count) | |
key, values = self_sort[choices_index] | |
values.each do |val| | |
chosen[key] = val | |
if choices_index + 1 < self_count | |
acc = recursive_permute_arrays(acc, choices_index + 1, chosen, self_sort, self_count) | |
else | |
acc << chosen.dup | |
end | |
end | |
acc | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment