2
$\begingroup$

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.

$\endgroup$

3 Answers 3

10
$\begingroup$
Flatten[ConstantArray[#,#] & /@ {3,1,2}]

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

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

Using MapThread and Splice (new in 12.1)

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

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

$\endgroup$
2
$\begingroup$

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}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.