1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Array
# Produces an array of arrays of all possible combinations
# of the given arrays in the positions given. (Imagine
# it like a slot machine dial. This gives every combination
# that could come up.)
#
# a = %w|a b|
# b = %w|a x|
# c = %w|x y|
# Enumerable.combinations(a, b, c).each { |x| p x }
#
# produces
#
# ["a", "a", "x"]
# ["a", "a", "y"]
# ["a", "x", "x"]
# ["a", "x", "y"]
# ["b", "a", "x"]
# ["b", "a", "y"]
# ["b", "x", "x"]
# ["b", "x", "y"]
#
# CREDIT: Florian Gross
def self.combinations(head, *rest)
crest = rest.empty? ? [[]] : combinations(*rest)
head.inject([]) { |combs, item|
combs + crest.map { |comb| [item] + comb }
}
end
end
|