Repeat elements in list, but the number of times each element is repeated is provided by a separate list
Join @@ MapThread[Table, {A,B}]
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
Join @@ Table @@@ Transpose @ {A,B}
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
Join @@ MapThread[ConstantArray, {A, B}]
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
Also
Internal`RepetitionFromMultiplicity @ Transpose[{A, B}]
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
kglr's proposals are nice, and the last (undocumented) one is very nice. As a variation, here is a solution using Inner[]
+ Flatten[]
:
Flatten[Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, List]]
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
As kglr notes, a shorter version is
Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, Join]
or in version 10 and later,
Inner[Table, {1, 2, 3, 4}, {3, 1, 4, 2}, Join]
a = {1, 2, 3, 4};
b = {3, 1, 4, 2};
Using ConstantArray
c = Flatten[ConstantArray[#[[1]], #[[2]]] & /@
Transpose[{a, b}]]
(* {1, 1, 1, 2, 3, 3, 3, 3, 4, 4} *)
or using Table
c = Flatten[Table[#[[1]], {#[[2]]}] & /@
Transpose[{a, b}]]
(* {1, 1, 1, 2, 3, 3, 3, 3, 4, 4} *)