■
nからはじまるrests.total個の要素を
rests[0]個,rests[1]個,…,rests[n]個に分ける全ての分割の仕方を生成する
[ Array::totalの本体は self.inject(0){|x,y| x+y } と定義されてるつもり ]
def split_sequence(n,rests,groups=Array.new(rests.length){ [] }, &block) if rests.all?{|x| x == 0 } block.call(groups) else rests.each_index{|i| if rests[i] > 0 rests[i] -= 1 groups[i].push(n) split_sequence(n.succ,rests,groups,&block) groups[i].pop rests[i] += 1 end } end end
使い方は
# 0から6までの数字を3個と4個に分ける分割を全て表示 split_sequence(0, [3,4]){|g| p g }
7C3 = 35個の組み合わせが表示されている
http://ideone.com/1faZx