正如@sawa 指出的那样,您的结果可能混淆了。我猜传递 2 得到 8 个元素,而不是 6,传递 3 得到 27,而不是 9。
您可以充分利用Array#repeated_combination
来生成要重复每个元素的次数:
class Array
def with_every_possibility_of_multiples(n)
(1..n).to_a.repeated_permutation(size).map do |repeats|
zip(repeats).flat_map{|elem, nb| [elem] * nb}
end
end
end
food = %w[eggs bacon sausage]
food.with_every_possibility_of_multiples(2) # =>
[["eggs", "bacon", "sausage"], ["eggs", "bacon", "sausage", "sausage"], ["eggs", "bacon", "bacon", "sausage"],
["eggs", "bacon", "bacon", "sausage", "sausage"],
["eggs", "eggs", "bacon", "sausage"],
["eggs", "eggs", "bacon", "sausage", "sausage"],
["eggs", "eggs", "bacon", "bacon", "sausage"],
["eggs", "eggs", "bacon", "bacon", "sausage", "sausage"]]
food.with_every_possibility_of_multiples(3) # =>
[["eggs", "bacon", "sausage"],
["eggs", "bacon", "sausage", "sausage"],
["eggs", "bacon", "sausage", "sausage", "sausage"],
["eggs", "bacon", "bacon", "sausage"],
["eggs", "bacon", "bacon", "sausage", "sausage"],
["eggs", "bacon", "bacon", "sausage", "sausage", "sausage"],
["eggs", "bacon", "bacon", "bacon", "sausage"],
["eggs", "bacon", "bacon", "bacon", "sausage", "sausage"],
["eggs", "bacon", "bacon", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "bacon", "sausage"],
["eggs", "eggs", "bacon", "sausage", "sausage"],
["eggs", "eggs", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "bacon", "bacon", "sausage"],
["eggs", "eggs", "bacon", "bacon", "sausage", "sausage"],
["eggs", "eggs", "bacon", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "bacon", "bacon", "bacon", "sausage"],
["eggs", "eggs", "bacon", "bacon", "bacon", "sausage", "sausage"],
["eggs", "eggs", "bacon", "bacon", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "sausage"],
["eggs", "eggs", "eggs", "bacon", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "sausage", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "bacon", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "bacon", "sausage", "sausage"],
["eggs", "eggs", "eggs", "bacon", "bacon", "bacon", "sausage", "sausage", "sausage"]]
请注意,这repeated_permutation
是 Ruby 1.9.2 的新内容。您可以require 'backports'
在早期版本中,或使用更丑陋的版本product
:
# ...
(1..n).to_a.product(*[(1..n).to_a] * (size-1)).map do |repeats|
# ...