# Expanding integer compositions

Quick version: I would like Mathematica code that, for instance, turns {3,1,2} into {3,3,3,1,2,2}. More formally, given positive integers $$c_1, \ldots, c_t$$ which sum to $$n$$, produce the length $$n$$ list where each $$c_i$$ appears $$c_i$$ times in the original order.

Mathematical background: The list $$\{c_1, \ldots, c_t\}$$ is a composition of $$n$$, akin to an integer partition of $$n$$ where "order matters." The desired expansion is similar to the combinatorial representation of compositions using squares, dominos, generally $$1 \times k$$ blocks. So $$\{3,1,2\}$$ would be, left to right, a $$1 \times 3$$ block, a square, then a domino.

Motivation: Being able to get these representations in Mathematica would allow exploration of how much two compositions "agree" by counting the number of positions with the same numeral, e.g.,

$$\{3,1,2\}$$ ~ $$\{3,3,3,1,2,2\}$$ and $$\{1,3,1,1\}$$ ~ $$\{1,3,3,3,1,1\}$$

agree in two positions.

Flatten[ConstantArray[#,#] & /@ {3,1,2}]


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

• Wonderful! I suspected there was a simple way to do this. Commented Apr 18, 2019 at 13:33
a = {3, 1, 2};


Using MapThread and Splice (new in 12.1)

MapThread[Splice @* Table, {a, a}]


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

Using SequenceReplace:

a = {3, 1, 2};
SequenceReplace[a, {b_Integer} :> Splice@Table[b, b]]


For versions prior to v12.1

SequenceReplace[a, {b_Integer} :> Sequence @@ Table[b, b]]


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