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}

  • $\begingroup$ Wonderful! I suspected there was a simple way to do this. $\endgroup$ – Brian Hopkins Apr 18 at 13:33

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.