Array#repeated_permutation() で重複順列を作成する
Array#repeated_permutation() は、与えられた配列要素から重複を許す順列を作成します (Ruby 1.9.2〜)。
例えば、[1, 2] という配列から、長さ 3 の重複順列を作成すると、以下のような組み合わせが得られます。
[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2]
[2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]
[1, 2].repeated_permutation(3) do |perm|
p perm
end[1, 2].repeated_permutation(3) do |a, b, c|
puts "#{a}, #{b}, #{c}"
end自力で重複順列を作成する
以下のような多重ループを使えば、repeated_permutation と同じ結果を簡単に得られます。
ただし、Ruby 1.9.2 以上を使用できるのなら、素直に repeated_permutation を使った方がシンプルに記述できます。
arr = [1, 2]
arr.each do |a|
arr.each do |b|
arr.each do |c|
puts "#{a}, #{b}, #{c}"
end
end
end