24
\$\begingroup\$

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] []
\$\endgroup\$
2
  • \$\begingroup\$ Related \$\endgroup\$ Commented Oct 2, 2022 at 19:24
  • 7
    \$\begingroup\$ Pretty sure this is run-length decoding, just with the runs and the lengths separated. \$\endgroup\$ Commented Oct 2, 2022 at 23:04

52 Answers 52

10
\$\begingroup\$

Jelly, 1 byte

x

Try it online!

\$\endgroup\$
8
\$\begingroup\$

Haskell, 27 bytes

(concat.).zipWith replicate

Try it online!

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

\$\endgroup\$
8
\$\begingroup\$

J, 1 byte

#

Try it online!

Simple built-in solution: The copy verb.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.
\$\endgroup\$
6
\$\begingroup\$

JavaScript (Node.js), 44 43 bytes

−1 thanks to Arnauld.

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

Try it online!

\$\endgroup\$
0
6
\$\begingroup\$

Python 3, 42 41 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!

\$\endgroup\$
2
  • \$\begingroup\$ 41 bytes \$\endgroup\$ Commented Oct 2, 2022 at 22:43
  • \$\begingroup\$ 40 bytes swapping arguments and outputting tuples. \$\endgroup\$ Commented Oct 3, 2022 at 15:12
5
\$\begingroup\$

APL (Dyalog Unicode), 1 byte

/

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Works in BQN too. \$\endgroup\$ Commented Oct 3, 2022 at 7:58
5
\$\begingroup\$

Pyth, 3 bytes

r9C

Test suite

Takes input as R,A.

\$\endgroup\$
5
\$\begingroup\$

Factor,  27  25 bytes

[ [ <array> ] 2map-flat ]

Try it online!

Takes input as R A.

\$\endgroup\$
5
\$\begingroup\$

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-

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

MATL, 2 bytes

Y"

Try it online! Or verify all test cases.

\$\endgroup\$
4
\$\begingroup\$

Octave, 7 bytes

repelem

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

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

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

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ In both cases, you can avoid the zip, iterate on a only and use b.shift for repeating \$\endgroup\$ Commented Oct 3, 2022 at 10:41
3
\$\begingroup\$

K (ngn/k), 4 bytes

,/#'

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Excel (ms365), 60 bytes

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

enter image description here


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

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

enter image description here

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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

Julia 1.0, 23 bytes

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

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Julia's fill saves a lot of bytes: 23 bytes \$\endgroup\$ Commented Oct 8, 2022 at 16:49
  • 1
    \$\begingroup\$ Thanks, Steffan! I replaced the code and changed this to a community wiki. \$\endgroup\$ Commented Oct 9, 2022 at 18:00
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Commented Oct 9, 2022 at 18:49
3
\$\begingroup\$

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!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 57 bytes \$\endgroup\$ Commented Nov 21, 2022 at 20:14
  • 1
    \$\begingroup\$ @jdt, very nice, although I hate that you used 0[b] unnecessarily ;-) \$\endgroup\$ Commented Nov 21, 2022 at 20:20
2
\$\begingroup\$

Charcoal, 9 bytes

IΣEθE§ηκι

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

   θ        Array of values
  E         Map over values
      η     Array of counts
     §      Indexed by
       κ    Current index
    E       Map over implicit range
        ι   Current value
 Σ          Concatenate arrays
I           Cast to string
            Implicitly print
\$\endgroup\$
2
\$\begingroup\$

PowerShell Core, 30 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 2 bytes

ÅΓ

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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;
};
\$\endgroup\$
2
\$\begingroup\$

I, 1 byte

\

Try it online!

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Answer must be at least 30 bytes; you entered 1. \$\endgroup\$ Commented Oct 5, 2022 at 13:53
2
\$\begingroup\$

Nim, 68 bytes

import sugar,sequtils
(x,y)=>concat zip(x,y).map x=>x[0].repeat x[1]

Attempt This Online!

-3 bytes thanks to Michael Chatiskatzi

\$\endgroup\$
1
  • \$\begingroup\$ You can save 3 bytes by applying the syntax tip \$\endgroup\$ Commented Oct 5, 2022 at 11:05
2
\$\begingroup\$

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)
\$\endgroup\$
1
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Oct 22, 2022 at 4:33
2
\$\begingroup\$

Uiua, 1 byte

Try it online!

\$\endgroup\$

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.