Skip to content

Instantly share code, notes, and snippets.

@dannvix
Created April 12, 2013 16:42
Show Gist options
  • Save dannvix/5373360 to your computer and use it in GitHub Desktop.
Save dannvix/5373360 to your computer and use it in GitHub Desktop.
for P piles with N items, generate all possible combinations without redundant
# for P piles with N items, generate all possible combinations without redundant
# e.g. for piles(5, 3) -> [(5,0,0), (4,1,0), (3,2,0), (3,1,1), (2,2,1)]
def make_piles (num, pile, piles=[], c=Array.new(pile, 0), idx=0)
if num == 0
piles.push(c.clone)
else
top = (c[idx-1] != 0) ? ((c[idx-1] > num) ? num : c[idx-1]) : (num)
top.downto(1).each do |i|
c[idx] = i
make_piles(num-i, pile, piles, c, idx+1)
c[idx] = 0
end
end
return piles
end
piles = make_piles(50, 50)
puts piles.map{|p| p.inspect}.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment