3
$\begingroup$

I'm trying to repeat each element of a list x number of times, where x is the corresponding element of the same position in another list.

For example, I have list A = {1,2,3,4} and another list B = {3,1,4,2} and I'm trying to get C = {1,1,1,2,3,3,3,3,4,4}.

How do I get C from A and B?

$\endgroup$
  • $\begingroup$ What have you tried? $\endgroup$ – Edmund Sep 18 '19 at 16:23
13
$\begingroup$
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}

|improve this answer|||||
$\endgroup$
5
$\begingroup$

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]
|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ shorter Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, Join] (+1) $\endgroup$ – kglr Sep 19 '19 at 14:10
  • $\begingroup$ Indeed, thank you! $\endgroup$ – J. M.'s technical difficulties Sep 21 '19 at 5:19
3
$\begingroup$
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} *)
|improve this answer|||||
$\endgroup$
3
$\begingroup$

Another way of approaching this is to define a function that carries out the basic task. In this case, to repeat the x element y times.

f[x_, y_] := ConstantArray[x, y]; SetAttributes[f, Listable]

Making this function Listable allows very simple calling method:

f[a, b] // Flatten
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}
|improve this answer|||||
$\endgroup$
0
$\begingroup$
a = {1, 2, 3, 4};
b = {3, 1, 4, 2};

Flatten[Table[a[[n]], {n, Length[a]}, {b[[n]]}]]
(* or *)
Flatten[Table[Table[a[[n]], {b[[n]]}], {n, Length[a]}]]

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

Flatten[Table[ConstantArray[a[[n]], b[[n]]], {n, Length[a]}]]

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

|improve this answer|||||
$\endgroup$

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.