@sawaが指摘しているように、おそらく結果がまちまちです。2を渡すと6ではなく8の要素が得られ、3を渡すと9ではなく27の要素が得られると思います。
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
これはRuby1.9.2の新機能であることに注意してください。require 'backports'
以前のバージョンで使用することも、次を使用して醜いバージョンを使用することもできますproduct
。
# ...
(1..n).to_a.product(*[(1..n).to_a] * (size-1)).map do |repeats|
# ...