Ruby 2.7.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Arrayクラス > repeated_combination
repeated_combination(n) { |c| ... } -> self
[permalink][rdoc]repeated_combination(n) -> Enumerator
サイズ n の重複組み合わせをすべて生成し、それを引数としてブロックを実行します。
得られる組み合わせの順序は保証されません。ブロックなしで呼び出されると、組み合わせを生成する Enumerator オブジェクトを返します。
a = [1, 2, 3]
a.repeated_combination(1).to_a #=> [[1], [2], [3]]
a.repeated_combination(2).to_a #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]
a.repeated_combination(3).to_a #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
# [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
a.repeated_combination(4).to_a #=> [[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,2,2],[1,1,2,3],
# [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],
# [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]
a.repeated_combination(0).to_a #=> [[]] # one combination of length 0
ブロックが与えられた場合、作成した配列の各要素を引数としてブロックを実行して self を返します。
a = [1, 2, 3]
result = []
a.repeated_combination(3) {|e| result << e} # => [1,2,3]
result #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
# [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
[SEE_ALSO] Array#repeated_permutation, Array#combination