Given an integer n and k, I want to create an array of all arrays of size k containing non-negative integers which sum to n. For example, if k=3 and n=10 I would want
[2,2,6]
[2,6,2]
[3,3,4]
[10,0,0]
etc....
Note that the order matters, which might make this easier. I know that there should be n+k-1 choose k-1 arrays in total.
My original idea was to just have k nested loops which would go through 0 to n on each element and then have an if statement at the end to check that the sum is n. This seems clumsy and very inefficient though, and I was wondering if there was a better way of doing it, ideally avoiding nested loops because I would like to be able to adjust k easily. Perhaps there is a relevant library? I am using Python.
This is what I have for k=4 and n=16 (yuck):
a=0
list = []
for i in range(17):
for j in range(17-i):
for k in range(17-i-j):
for l in range(17-i-j-k):
if i+j+k+l==16:
list.append([i,j,k,l])
a += 1