# Simple way to decompose a lists in a certain way?

I want to decompose one list into sublists (each sublist is given by certain lengh and the sum of every sublist is given by the maximun number in lists).

For example: lists={0,1,2,3,4}

all the sublists: {{0, 0, 4}, {0, 1, 3}, {0, 2, 2}, {0, 3, 1}, {0, 4, 0}, {1, 0, 3}, {1, 1, 2}, {1, 2, 1}, {1, 3, 0}, {2, 0, 2}, {2, 1, 1},{2, 2, 0}, {3, 0, 1}, {3, 1, 0}, {4, 0, 0}}

The code is as following:

Maxnum = 4;
setlength = 3;
lists = Table[i, {i, 0, Maxnum}];
ylists = Tuples[lists, setlength];
ysublists = {};
Do[If[Total[ylists[[j]]] == Maxnum, AppendTo[ysublists, ylists[[j]]]], {j, Length@ylists}];


I want to know whether this is any simple way to do the same work? Thank you in advance!

You may use FrobeniusSolve:

allTuples[len_, sum_] := FrobeniusSolve[ConstantArray[1, len], sum]
allTuples[3, 4]

(* {{0, 0, 4}, {0, 1, 3}, {0, 2, 2}, {0, 3, 1}, {0, 4, 0}, {1, 0, 3}, {1,
1, 2}, {1, 2, 1}, {1, 3, 0}, {2, 0, 2}, {2, 1, 1}, {2, 2, 0}, {3,
0, 1}, {3, 1, 0}, {4, 0, 0}} *)

• That's very simple and just one line code! Thank you!@C. E. Commented Sep 16, 2019 at 16:04

You can get there most of the way using IntegerPartitions, like this:

Maxnum = 4;
setlength = 3;
lists = Table[i, {i, 0, Maxnum}];

IntegerPartitions[Maxnum, {setlength}, lists]
(* {{4, 0, 0}, {3, 1, 0}, {2, 2, 0}, {2, 1, 1}} *)


As you can see, this will generate all sorted solutions. If you really need all possible permutations, you can use Permutations and Join:

Join @@
Permutations /@ IntegerPartitions[Maxnum, {setlength}, lists]
(* {{4, 0, 0}, {0, 4, 0}, {0, 0, 4}, {3, 1, 0}, {3, 0, 1}, {1, 3,
0}, {1, 0, 3}, {0, 3, 1}, {0, 1, 3}, {2, 2, 0}, {2, 0, 2}, {0, 2,
2}, {2, 1, 1}, {1, 2, 1}, {1, 1, 2}} *)

• Thank you very much! good idea to use Permutations and IntegerPartitions together, I didn't think of the Permutations before @Lukas Lang Commented Sep 16, 2019 at 16:06