2
$\begingroup$

I can use the Combinatorica package to produce all integer compositions of the integer $n$ into $k$ parts by writing Compositions[n,k]. However, I would like a table tat lists all compositions of $n$, not just those into $k$ parts. I am not too sophisticated with Mathematica. I have tried searching for a way to do this, but i am at a loss.

$\endgroup$
  • 2
    $\begingroup$ does this give you what you need: allCompositions[n_] := Join @@ (Compositions[n, #] & /@ Range[n])? $\endgroup$ – kglr Aug 23 '18 at 4:44
1
$\begingroup$
<< Combinatorica`
allCompositions[n_] : = Join @@ (Compositions[n, #] & /@ Range[n])

allCompositions[3]

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

Alternatively, you can define a function that returns the same (up to ordering) list:

  1. Using IntegerPartitions and Permutations:

allComps[n_] := Join @@ (DeleteDuplicates[Join @@ (Permutations /@ 
  PadLeft[IntegerPartitions[n, #]])] & /@Range[n])

Sort[allComps[5]] == Sort[allCompositions[5]]

True

  1. Using FrobeniusSolve:

allComps2[n_] := Join[{{n}}, 
   Join @@ (FrobeniusSolve[ConstantArray[1, #], n] & /@ Range[2, n])];

Sort[allComps[5]] == Sort[allComps2[5]]

True

$\endgroup$

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.