# Repeat Values In Array

Given two arrays of non-negative integers $$\A = [A_1,A_2,\ldots,A_n]\$$ and $$\R = [R_1,R_2,\ldots,R_n]\$$ which are equal in length, return an array which has the element $$\A_1\$$ repeated $$\R_1\$$ times, then element $$\A_2\$$ repeated $$\R_2\$$ times, all the way up to $$\A_n\$$.

Standard loopholes are forbidden. As this is , the shortest program wins.

### Test Cases

$$\A\$$ $$\R\$$ Output
[1,2,3] [1,2,3] [1,2,2,3,3,3]
[6,0,0,6] [5,1,1,0] [6,6,6,6,6,0,0]
[100,100] [0,0] []
• Related Oct 2, 2022 at 19:24
• Pretty sure this is run-length decoding, just with the runs and the lengths separated. Oct 2, 2022 at 23:04

# Jelly, 1 byte

x


Try it online!

# J, 1 byte

#


Try it online!

Simple built-in solution: The copy verb.

# R, 3 bytes

rep


Try it online!

In R many functions are vectorized and so is rep - it happens to work correctly for this challenge.

# Raku, 12 bytes

(*Zxx*).flat


Try it online!

• xx is Raku's replication operator. It produces a list of a number of copies of its left argument given by its right argument. (Very conveniently, though irrelevant for this problem, the left-hand side is re-evaluated the requested number of times, so for example rand xx 10 will produce a list of ten different random numbers.)
• Z is the zip "meta-operator." It can be prepended to any other operator to produce a new operator that zips two lists together using the original operator.
• The asterisks make this a "WhateverCode" expression, a short way of defining anonymous functions. The first and second argument to the function will take the place of the first and second asterisk, respectively.
• .flat flattens the list of replicated lists.

# Haskell, 27 bytes

(concat.).zipWith replicate


Try it online!

These built-ins have long names, but I haven't found anything shorter.

# JavaScript (Node.js), 44 43 bytes

−1 thanks to Arnauld.

A=>R=>A.flatMap((a,i)=>Array(R[i]).fill(a))


Try it online!

# Python 3, 4241 40 bytes

lambda*a:sum(map(lambda x,*y:x*y,*a),())


Try it online!

-1 thanks to Jonathan Allan!

-1 thanks to loopy walt!

• 41 bytes Oct 2, 2022 at 22:43
• 40 bytes swapping arguments and outputting tuples. Oct 3, 2022 at 15:12

# APL (Dyalog Unicode), 1 byte

/


Try it online!

# Pyth, 3 bytes

r9C


Test suite

Takes input as R,A.

# Factor,  27  25 bytes

[ [ <array> ] 2map-flat ]


Try it online!

Takes input as R A.

# Python NumPy, 39 bytes

lambda a,b:[0,*b]*1**b[:1]@[(),*zip(a)]


Attempt This Online!

Of course, there is also the repeat builtin.

### How?

Beside the usual bending over backwards to avoid the explicit numpy import this uses the fact that if we write $$\c_i = [b_i]\$$ then, formally, $$\c_1 a_1 + c_2 a_2 + ... + c_n a_n\$$ is a dot product. It is mildly tricky to set up an array of equal length sequences because numpy will just create an additional dimension and create an array of scalars. Here we prepend a different length sequence, forcing a ragged array (after using zip to create a list of singleton tuples). To match we must also prepend one value to the length array. The 1**b[:1] factor, mathematically a nop, is there to trigger a coercion cascade to numpy arrays-

# Vyxal, 4 bytes

¨£ẋf


Try it Online!

This two-byte solution should work, but it seems to bork when the length is an array only of zeros: Try it Online!

# MATL, 2 bytes

Y"


# Octave, 7 bytes

repelem


It seem's that TIO's version of Octave doesn't have this built-in.

• @LuisMendo The Octave version on my computer (7.2.0) has both repelem and repelems, and their usage are different. Oct 3, 2022 at 0:28
• Ah, so they finally introduced it. Nice Oct 3, 2022 at 9:23

# Goruby, 25 22 bytes

-3 bytes thanks to G B

->a,b{a.fl{[_1]*b.sh}}


Attempt This Online!

# Ruby, 33 31 bytes

-2 bytes thanks to G B

->a,b{a.flat_map{[_1]*b.shift}}


Attempt This Online!

• In both cases, you can avoid the zip, iterate on a only and use b.shift for repeating
– G B
Oct 3, 2022 at 10:41

# Desmos, 72 bytes

f(A,R)=[A[i<=∑_{n=1}^{[1...R.length]}R[n]][1]fori=[0...R.total][2...]]


Might post an explanation if I feel like it.

Try It On Desmos!

Try It On Desmos! - Prettified

# K (ngn/k), 4 bytes

,/#'


Try it online!

# Japt, 6 bytes

Takes R as the first input.
A byte or 2 could be saved if output could be a 2D-array but I'm guessing a flat array is one of the points of the challenge.

cÈÇYgV


Try it

cÈÇYgV     :Implicit input of arrays U=R & V=A
c          :Flat map U
È         :Pass each X at index Y through the following function
Ç        :  Map the range [0,X)
YgV     :    Index into V


# Brachylog, 9 bytes

z⟨kj₎t⟩ˢc


Try it online!

-2 bytes thanks to @DLosc.

-1 byte thanks to @Kroppeb

### Explanation

Given inputs [a1, …, an] and [r1, …, rn]:

z         Zip: [[a1,r1], ..., [an, rn]]
⟨    ⟩ˢ   For each sublist [ai, ri]
k         Take [ai]
t      Take ri
j₎       Juxtapose the list [ai] ri times to itself
c  Concatenate into one list

• @DLosc TIL I implemented this behaviour of = Oct 5, 2022 at 7:47
• Found a way to use juxtapose: z⟨kj₎t⟩ˢc with only 9 bytes Try it online! Oct 8, 2022 at 19:23
• @Kroppeb Very nice, using k to get a list and not a simple integer. Oct 8, 2022 at 22:18

# Julia 1.0, 23 bytes

a^b=vcat(fill.(a,b)...)


Try it online!

• Julia's fill saves a lot of bytes: 23 bytes Oct 8, 2022 at 16:49
• Thanks, Steffan! I replaced the code and changed this to a community wiki. Oct 9, 2022 at 18:00
• Note that you don't need to change to a community wiki because someone golfed your answer. See codegolf.meta.stackexchange.com/a/9692/92689 Oct 9, 2022 at 18:49

# C (clang), 59 55 bytes

• -2 bytes thanks to @jdt.
f(*a,*b,n){for(;n;)~--*b?printf("%d ",*a):a++-b++-n--;}


Try it online!

• 57 bytes
– jdt
Nov 21, 2022 at 20:14
• @jdt, very nice, although I hate that you used 0[b] unnecessarily ;-)
– c--
Nov 21, 2022 at 20:20

# Charcoal, 9 bytes

ＩΣＥθＥ§ηκι


Attempt This Online! Link is to verbose version of code. Explanation:

   θ        Array of values
Ｅ         Map over values
η     Array of counts
§      Indexed by
κ    Current index
Ｅ       Map over implicit range
ι   Current value
Σ          Concatenate arrays
Ｉ           Cast to string
Implicitly print


# PowerShell Core, 30 bytes

param($a,$r)$r|%{,$a[$i++]*$_}


Try it online!

# 05AB1E, 2 bytes

ÅΓ


Try it online!

# Excel (ms365), 60 bytes

=IFERROR(TEXTSPLIT(CONCAT(REPT(A1:C1&"|",A2:C2)),"|",,1),"")


Or, if you don't mind whole rows as input arrays, for 56 bytes:

=IFERROR(TEXTSPLIT(CONCAT(REPT(1:1&"|",2:2)),"|",,1),"")


# simply, 87 bytes

The code defines an anonymous function that returns the expected result.
Nothing special here...

fn($A$R){$X=[]each$R as$k=>$v;if$v$X=&array_concat($X&array_fill($A[$k]$v))send$X;}  ## Usage Just use it normally... Example using the 2nd test case. $fn = fn($A$R){$X=[]each$R as$k=>$v;if$v$X=&array_concat($X&array_fill($A[$k]$v))send$X;} // should output: 6,6,6,6,6,0,0 echo &join(call$fn([6,0,0,6], [5,1,1,0]), ',');


Since it is an anonymous function, using call is required.

## Ungolfed

This code does exactly the same as the golfed version.

This is pretty close to pseudo-code.

Set $fn to an anonymous function($A, $R) Begin. Define the variable$result = [].
Loop through $R as value$value key $key. Begin. If$value then.
Begin.
Set $result to the result of calling &array_concat($result,
&array_fill($A[$key], $value) ). End. End. Return the$result.
End.


A little further from pseudo-code...

$fn = fn($A, $R) => {$result = [];
foreach $R as$key => $value { if$value {
$result = &array_concat($result,
&array_fill($A[$key], $value) ); } } return$result;
};


# I, 1 byte

\


Try it online!

Body must be at least 30 characters; you entered 27.

• Answer must be at least 30 bytes; you entered 1. Oct 5, 2022 at 13:53

# Pip-p, 16 bytes

{FA({aRLb}MZab)}


Try It Online!

{FA({aRLb}MZab)}     ; First argument = A = a
; Second argument = B = b
{              }     ; Create a function that...
MZab       ; maps a and b (as zipped pairs of elements) to...
{aRLb}           ; a block that repeats the (first argument) by (second argument)...
FA(          )      ; and flattens the resulting list
; (after which the list is implicitly printed out)

• The inner function can be a lambda expression: _RL B is the direct translation (_ is the same as {a} and B is the same as {b}), but you can save a byte if you flip the arguments: BRL_MZba. Then you can drop the outer curly braces, making it a full program rather than a function, using the -x flag to evaluate the inputs as lists: DSO Oct 22, 2022 at 4:33

# MathGolf, 7 bytes

mÅaam*─


Try it online.

Or alternatively, with the input-lists swapped:

^mæ~Ä_;


Try it online.

Explanation:

m     # Map over the first (implicit) input-list,
Å    # using two characters as inner code-block:
a   #  Wrap it into a list
a  #  Wrap that into a list
# (e.g. [6,0,0,6] → [[[6]],[[0]],[[0]],[[6]]])
m*    # Repeat each the second (implicit) input amount of times
# (e.g. [5,1,1,0] and [[[6]],[[0]],[[0]],[[6]]] →
#  [[[6,6,6,6,6]],[[0]],[[0]],[[]]])
─     # Flatten it to a single list
# (e.g. [[[6,6,6,6,6]],[[0]],[[0]],[[]]] → [6,6,6,6,6,0,0])
# (after which the entire stack is output implicitly as result)


Unfortunately, using m* on lists [6,0,0,6] and [5,1,1,0] results in [30,0,0,0] and lists [[6],[0],[0],[6]] and [5,1,1,0] results in [[30],[0],[0],[0]] (apparently..). Hence the need for two wraps before we can use m*.

^        # Zip the two (implicit) input-lists together
# (e.g. [5,1,1,0] and [6,0,0,6] → [[6,5],[0,1],[0,1],[6,0]]
m       # Map over each inner pair,
æ      # using 4 characters as inner code-block:
~     #  Pop and push the contents of the pair separately to the stack
Ä    #  Pop the top, and loop that many times:
_   #   Duplicate
;  #  After the inner loop, discard the top item
# (after which the entire stack is output implicitly as result)


# Husk, 1 byte

Ṙ


Try it online!

Built-in solution. Input is arg1=R, arg2=A

# Husk, 5 bytes

Σz(↑∞


Try it online!

Roll-your-own solution avoiding Ṙ built-in.

Σz(↑∞
z     # zip the two inputs together with
(    #   combination of functions:
∞  #   make an infinite list of copies of arg1
↑   #   and then take arg2 elements from it;
Σ      # finally, flatten the output