# Find All Compositions of an Integer

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.

• does this give you what you need: allCompositions[n_] := Join @@ (Compositions[n, #] & /@ Range[n])? – kglr Aug 23 '18 at 4:44

## 1 Answer

<< Combinatorica
allCompositions[n_] : = Join @@ (Compositions[n, #] & /@ Range[n])

allCompositions


{{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] == Sort[allCompositions]


True

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

Sort[allComps] == Sort[allComps2]
`

True