3
$\begingroup$

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!

$\endgroup$
4
$\begingroup$

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}} *)
$\endgroup$
  • $\begingroup$ Thank you very much! good idea to use Permutations and IntegerPartitions together, I didn't think of the Permutations before @Lukas Lang $\endgroup$ – Xuemei Gu Sep 16 at 16:06
4
$\begingroup$

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}} *)
$\endgroup$
  • $\begingroup$ That's very simple and just one line code! Thank you!@C. E. $\endgroup$ – Xuemei Gu Sep 16 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.