4
$\begingroup$

I recently asked the question (Computationally Employ Sum over Ordered Partitions?) which I think I can work through. But there's a subtelty I overlooked before that problem is even well-defined, which is maybe deserving of its own question.

I'm interested in considering ordered partitions of an integer $n$. However, using a built in function like IntegerPartitions the output will be in the form, for example:

{{3,0},{2,1},{1,2},{1,1,1}}

What I would like to do is have Mathematica write these ordered partitions as $n$-tuples. What I mean by this is best illustrated with an example. Consider $n=3$ objects, for a small $n$ example. There are two slots between the objects where we can place barriers.

$$\{\, \cdot \, | \, \cdot \, | \, \cdot \}$$

I would like the above ordered partition to be given in Mathematica by {1,1,1}.

$$\{\, \cdot \, \, \cdot \, | \, \cdot \}$$

The above partition, I want to write as {2,0,1} because there is no barrier in the first slot.

$$\{\, \cdot \, | \, \cdot \, \, \cdot \}$$

The above I want to write as {1,2,0} and of course...

$$\{\, \cdot \, \, \cdot \, \, \cdot \}$$

this I want to write as {3,0,0}. Is there a way I can manipulate Mathematica's built-in function IntegerPartitions to do this for any $n$?

$\endgroup$
6
$\begingroup$
orderedPartitions[n_] := Flatten[#, 1] &@(Permutations /@ IntegerPartitions[n]);
paddedOrderedParitions[n_] := Flatten /@ (orderedPartitions[n] 
/. {x_Integer /; x != 1 :> PadRight[{x}, x]});

n=3,

{{3, 0, 0}, {2, 0, 1}, {1, 2, 0}, {1, 1, 1}}

n=5,

{{5, 0, 0, 0, 0}, {4, 0, 0, 0, 1}, {1, 4, 0, 0, 0}, {3, 0, 0, 2, 0}, {2, 0, 3, 0, 0}, {3, 0, 0, 1, 1}, {1, 3, 0, 0, 1}, {1, 1, 3, 0, 0}, {2, 0, 2, 0, 1}, {2, 0, 1, 2, 0}, {1, 2, 0, 2, 0}, {2, 0, 1, 1, 1}, {1, 2, 0, 1, 1}, {1, 1, 2, 0, 1}, {1, 1, 1, 2, 0}, {1, 1, 1, 1, 1}}

$\endgroup$
  • $\begingroup$ Works perfectly, thank you! Also, with your help earlier on that other question I think I can do what I was originally hoping. Very much appreciated. $\endgroup$ – Benighted Jun 12 '17 at 7:52
  • $\begingroup$ What's the logic for generating eg {3,0,0,2,0} rather than {3,0,0,0,2}? $\endgroup$ – evanb Jun 12 '17 at 8:49
  • $\begingroup$ OH, I see. 3,0,0 because 3 takes up 3 slots! Smart. $\endgroup$ – evanb Jun 12 '17 at 8:51
  • 3
    $\begingroup$ Except[1, x_Integer] is somewhat more efficient than x_Integer /; x != 1 $\endgroup$ – Mr.Wizard Jun 12 '17 at 9:43

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.