func part(_, {.is_empty}) { [[]] } func partitions({.is_empty}) { [[]] } func part(s, args) { gather { s.combinations(args[0], { |*c| part(s - c, args.ft(1)).each{|r| take([c] + r) } }) } } func partitions(args) { part(@(1..args.sum), args) } [[],[0,0,0],[1,1,1],[2,0,2]].each { |test_case| say "partitions #{test_case}:" partitions(test_case).each{|part| say part } print "\n" }