39
\$\begingroup\$

There was a challenge up a while ago about multiplying strings. It showed us how we can multiply not only numbers, but also strings. However, we still can't multiply a number by a string properly. There has been one attempt to do so but this is obviously wrong. We need to fix that!

Your Task:

Write a function or program that multiplies two inputs, a string and an integer. To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).

Input:

A string that consists solely of printable ASCII characters and newlines, and an integer (possible negative).

Output:

The string multiplied by the integer.

Examples:

Hello World!, 3            --> HHHeeellllllooo   WWWooorrrlllddd!!!
foo, 12                    --> ffffffffffffoooooooooooooooooooooooo
String, -3                 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 --> 
Hello
World!, 2                  --> HHeelllloo

                               WWoorrlldd!!

Scoring:

This is , lowest byte count wins!

\$\endgroup\$
6
  • 5
    \$\begingroup\$ Can we assume the string is printable ASCII-only, plus newlines? \$\endgroup\$
    – mbomb007
    Jul 11, 2017 at 21:45
  • \$\begingroup\$ Can we output a list of strings? \$\endgroup\$ Jul 11, 2017 at 21:50
  • \$\begingroup\$ Partial solution in Retina. Only works for positive values of the integer. I probably won't make time to finish it if someone wants to. tio.run/##K0otycxL/P8/… \$\endgroup\$
    – mbomb007
    Jul 11, 2017 at 21:59
  • \$\begingroup\$ @mbomb007, yes, sorry for taking so long about that. \$\endgroup\$
    – Gryphon
    Aug 2, 2017 at 0:08
  • \$\begingroup\$ @totallyhuman, no you may not. \$\endgroup\$
    – Gryphon
    Aug 8, 2017 at 3:52

57 Answers 57

32
\$\begingroup\$

Jelly, 6 5 4 bytes

²Ɠxm

Try it online!

How it works

²Ɠxm  Main link. Argument: n (integer)

²     Yield n².
 Ɠ    Read and eval one line of input. This yields a string s.
  x   Repeat the characters of s in-place, each one n² times.
   m  Takes each |n|-th character of the result, starting with the first if n > 0, 
      the last if n < 0.
\$\endgroup\$
13
  • 1
    \$\begingroup\$ OK, now I'm really impressed. I'd love an explanation of this particular wonder in miniature. \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 21:12
  • \$\begingroup\$ Sure. As soon as I made a test suite and am done golfing. \$\endgroup\$
    – Dennis
    Jul 11, 2017 at 21:18
  • 5
    \$\begingroup\$ OK, if you can make this any smaller, I'm going to give up trying to make a question that will take you >10 bytes. \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 21:19
  • 14
    \$\begingroup\$ OK, that's it. I'm learning Jelly. I want to be able to do magic too. \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 21:31
  • 2
    \$\begingroup\$ We all know how a discussion about Jelly chains ends up being a mess... \$\endgroup\$ Jul 12, 2017 at 9:11
10
\$\begingroup\$

JavaScript (ES6), 63 bytes

Takes input in currying syntax (s)(n).

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

Test cases

let f =

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

console.log(f(`Hello World!`)(3))
console.log(f(`foo`)(12))
console.log(f(`String`)(-3))
console.log(f(`This is a fun challenge`)(0))
console.log(f(`Hello
World!`)(2))

\$\endgroup\$
0
10
\$\begingroup\$

Python 3, 44 bytes

f=lambda s,n:s and s[0]*n+f(s[1:],n)+s[0]*-n

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ The base case seems to ignore the last character. \$\endgroup\$
    – xnor
    Jul 11, 2017 at 21:45
  • \$\begingroup\$ Not quite sure why I did that... Thanks! \$\endgroup\$
    – Dennis
    Jul 11, 2017 at 21:46
  • 2
    \$\begingroup\$ 41 bytes. but idk if a function call as f(n,*s) is considered valid \$\endgroup\$ Jul 12, 2017 at 13:39
9
\$\begingroup\$

Python 2, 59 57 50 46 bytes

-2 bytes thanks to Anders Kaseorg. -4 bytes thanks to Dennis.

lambda s,n:''.join(i*n**2for i in s)[::n or 1]

Try it online!

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

05AB1E, 10 bytes

S²Ä×J²0‹iR

Try it online!

S          # Split the string into characters
 ²Ä×       # Repeat each character abs(integer) times
    J      # Join into a string
     ²0‹i  # If the integer is less than 0...
         R #   Reverse the string
\$\endgroup\$
6
  • \$\begingroup\$ TFW you spend 30 minutes trying to come up with something to prove to @Riley that ²0‹i isn't the best route and come up with literally 0 alternatives. \$\endgroup\$ Jul 11, 2017 at 21:17
  • \$\begingroup\$ @MagicOctopusUrn I've used something like ²0‹i before and I always think there has to be something better. \$\endgroup\$
    – Riley
    Jul 11, 2017 at 21:19
  • \$\begingroup\$ I think I've tried to find an alternative around 10 times now... wasting a cumulative 3 hours of my life ._. Ä.D)øJ¹0‹iR is the best I can do without copying you, I think yours is optimized. \$\endgroup\$ Jul 11, 2017 at 21:20
  • \$\begingroup\$ If you care, Emigna used è here, though I can't find a way to apply it in this scenario. Would save a maximum of 1 byte, if that. \$\endgroup\$ Jul 11, 2017 at 21:53
  • \$\begingroup\$ SÂΛ@²Ä×J, using Î to push 0 and input works if you change the order. Saves 1 byte! (Also replaced the if, so it doesn't need to be closed) \$\endgroup\$
    – kalsowerus
    Jul 12, 2017 at 8:15
6
\$\begingroup\$

R, 83 78 76 74 bytes

function(s,i)cat('if'(i<0,rev,I)(rep(el(strsplit(s,'')),e=abs(i))),sep='')

Anonymous function.

Frederic saved 3 bytes, Giuseppe saved 2 4, pajonk saved 2.

Explanation:

     el(strsplit(s,''))                      # split string into list characters
 rep(                  ,e=abs(i)))           # repeat each character abs(i) times


    'if'(i<0,rev, ){...}                     # if i>0, reverse character list
                 I                           # otherwise leave it alone: I is the identity function
cat(                    ,sep='')             # print the result

Tests:

> f('Hello World!', 3 )
HHHeeellllllooo   WWWooorrrlllddd!!!
> f('foo', 12)
ffffffffffffoooooooooooooooooooooooo
> f('String', -3)
gggnnniiirrrtttSSS
> f('This is a fun challenge', 0)
> f('Hello
+ World!', 2)
HHeelllloo

WWoorrlldd!!
\$\endgroup\$
11
  • 2
    \$\begingroup\$ Well done ! You could save a few bytes by writing rep(foo,,,3) or rep(foo,e=3) (same lenght) ;-) \$\endgroup\$
    – Frédéric
    Jul 11, 2017 at 22:12
  • \$\begingroup\$ @Frédéric you beat me to it, I was going to say the same thing! \$\endgroup\$
    – Giuseppe
    Jul 11, 2017 at 22:13
  • 1
    \$\begingroup\$ yeah, no problem! Basically, I wanted to get rid of the braces, so I needed to get rid of a=. Hence, I used the value of a as an argument to the reverse function if i<0, by having the conditional return the function (which is why I needed the backquotes). But I needed to also apply the identity function for the i>=0 case, so I used ( which is close enough. ( is in fact a function. R is weird. \$\endgroup\$
    – Giuseppe
    Jul 11, 2017 at 22:39
  • 1
    \$\begingroup\$ btw, the R docs for Paren say that ( is semantically equivalent to the identity function(x)x \$\endgroup\$
    – Giuseppe
    Jul 12, 2017 at 20:24
  • 1
    \$\begingroup\$ 76 bytes \$\endgroup\$
    – Giuseppe
    Dec 7, 2017 at 19:10
5
\$\begingroup\$

MATL, 9 bytes

y|Y"w0<?P

Inputs are: number, then string.

Strings with newlines are input using char 10 as follows: ['first line' 10 'second line'].

Try it online! Or verify all test cases.

Explanation

Consider inputs -3 and 'String'.

y      % Implicitly take two inputs. Duplicate from below
       % STACK: -3, 'String', -3
|      % Absolute value
       % STACK: -3, 'String', 3
Y"     % Run-length decoding
       % STACK: -3, 'SSStttrrriiinnnggg'
w      % Swap
       % STACK: 'SSStttrrriiinnnggg', -3
0<     % Less than 0?
       % STACK: 'SSStttrrriiinnnggg', 1
?      % If so
  P    %   Flip
       %   STACK: 'gggnnniiirrrtttSSS'
       % End (implicit). Display (implicit)
\$\endgroup\$
5
\$\begingroup\$

Haskell, 41 36 bytes

f n|n<0=reverse.f(-n)|1<3=(<*[1..n])

Try it online!

Example usage: f (-3) "abc" yields "cccbbbaaa".

Edit: -5 bytes thanks to xnor!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ There's (<*[1..n]) for ((<$[1..n])=<<). \$\endgroup\$
    – xnor
    Jul 11, 2017 at 22:22
  • \$\begingroup\$ @xnor Thanks! That's good to know. \$\endgroup\$
    – Laikoni
    Jul 12, 2017 at 5:58
5
\$\begingroup\$

V, 29, 23, 18, 17 bytes

æ_ñÀuñÓ./&ò
ÀäëÍî

Try it online!

Hexdump:

00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd  ._..u.../&......
00000010: ee                                       .

Thanks to @nmjcman101 for saving 6 bytes, which encouraged me to save another 5!

The original revision was pretty terrible, but now I'm really proud of this answer because it handles negative numbers surprisingly well. (V has next to no numerical support and no support for negative numbers)

Explanation:

æ_          " Reverse the input
  ñ  ñ      " In a macro:
   À        "   Run the arg input. If it's positive it'll give a count. If it's negative
            "   running the '-' will cause V to go up a line which will fail since we're
            "   on the first line, which will break out of this macro
    u       "   (if arg is positive) Undo the last command (un-reverse the line)
      Ó./&ò " Put every character on it's own line

At this point, the buffer looks like this:

H
e
l
l
o

w
o
r
l
d
!
<cursor>

It's important to not the trailing newline, and that the cursor is on it.

À           " Run arg again. If it's negative, we will move up a line, and then give the 
            " absolute value of the count. If it's positive (or 0) it'll just give the
            " count directly (staying on the last line)
 ä          " Duplicate... (count times)
  ë         "   This column. 
   Íî       " Remove all newlines.
\$\endgroup\$
4
  • \$\begingroup\$ A few bytes for ya Try it online! I always hate the "Negative numbers mean something else!" edge case too. This is a case where your 0 special cases in V came in super handy. \$\endgroup\$
    – nmjcman101
    Jul 12, 2017 at 2:12
  • \$\begingroup\$ Sorry about the negative numbers special. However, a lot of answers managed to incorporate that into their main answer. Impressive on this V one though. \$\endgroup\$
    – Gryphon
    Jul 12, 2017 at 13:51
  • \$\begingroup\$ @nmjcman101 Oh wow, that's so obvious, I don't know how I didn't think of it. Thank you! \$\endgroup\$
    – DJMcMayhem
    Jul 12, 2017 at 16:47
  • \$\begingroup\$ @Gryphon Oh I know. The challenge is fine, I just dislike my own language for being so bad at what it's supposed to be good at. :P \$\endgroup\$
    – DJMcMayhem
    Jul 12, 2017 at 16:48
5
\$\begingroup\$

J, 19 15 13 bytes

(#~|)A.~0-@>]

Try it online!

Explanation

        0-@>]      NB. first or last index depending on sign of right arg
     A.~           NB. get first or last Anagram of left arg
(#~|)              NB. copy left arg, absolute-value-of-right-arg times
\$\endgroup\$
5
  • 2
    \$\begingroup\$ (#~|)A.~0-@>] for 13 bytes \$\endgroup\$
    – miles
    Jul 12, 2017 at 19:48
  • \$\begingroup\$ Very nice @miles ! \$\endgroup\$
    – Tikkanz
    Jul 12, 2017 at 20:20
  • \$\begingroup\$ No problem. You also don't need to count the parentheses used to invoke the verb. \$\endgroup\$
    – miles
    Jul 12, 2017 at 23:20
  • 2
    \$\begingroup\$ Also 13 bytes: #~ ::(|.@#~|) \$\endgroup\$
    – FrownyFrog
    Dec 8, 2017 at 12:26
  • \$\begingroup\$ @FrownyFrog Nice! \$\endgroup\$
    – Jonah
    Jan 6, 2023 at 20:14
4
\$\begingroup\$

05AB1E, 10 bytes

0‹FR}ʒ¹Ä×?

Try it online!

Explanation

0‹F         # input_1 < 0 times do:
   R        # reverse input_2
    }       # end loop
     ʒ      # filter
      ¹Ä×   # repeat current char abs(input_1) times
         ?  # print without newline
\$\endgroup\$
4
\$\begingroup\$

PHP>=7.1, 65 bytes

for([,$s,$n]=$argv;$i<strlen($s)*abs($n);)echo$s[$i++/$n-($n<0)];

PHP Sandbox Online

\$\endgroup\$
1
  • 1
    \$\begingroup\$ In integer context, $n<0 has the same value as $n<0?:0 but it's 3 bytes shorter :-) \$\endgroup\$
    – axiac
    Jul 12, 2017 at 12:01
4
\$\begingroup\$

Brain-Flak (BrainHack), 154 152 bytes

([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}

Try it online!

Just here to give DJMcMayhem some competition. ;)

Explanation

Here's a modified version of DJMcMayhem's explanation

#Compute the sign and negative absolute value 
([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>

#Keep track of the sign
({}<

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>())>[()]}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the sign back on
>)

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}
\$\endgroup\$
4
+100
\$\begingroup\$

Elm, 69 bytes

f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

Defines f to be a function that takes an integer and a list of characters and returns a list of characters. You can try it here. Here is a full test program:

import Html exposing (text)

f : Int -> List Char -> List Char
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

main =
  text (String.fromList (f -3 ['S','t','r','i','n','g']))

Explanation

This is my first Elm submission, so please let me know any golfing tricks I've missed.

Using currying, we define a function f that takes an integer n and returns a function from a list of chars to a list of chars. There are two cases in the function definition:

  • If n is negative, call f on its absolute value (f -n); then compose (>>) the resulting function with List.reverse.
  • Else, create a function that puts n copies of a value in a list (List.repeat n) and map that function over each char in the list, flattening the result into a list of chars (List.concatMap).
\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 15 bytes

{⌽⍣(⍵<0)⊢⍺/⍨|⍵}

String as a left argument, number as a right argument.

Try it online!

How?

⍺/⍨ - repeat the string

|⍵ - abs(number) times

⌽⍣ - reverse if

(⍵<0) - the number is below 0

\$\endgroup\$
3
  • \$\begingroup\$ Umm, it'd be nice if the TIO like worked? \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 21:02
  • \$\begingroup\$ @Gryphon and here goes the byte... \$\endgroup\$
    – Uriel
    Jul 11, 2017 at 21:06
  • \$\begingroup\$ Yep, I'd just realized that and was typing out my comment to tell you. \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 21:06
3
\$\begingroup\$

MATLAB, 37 bytes

@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

This defines and anonymous function with inputs s: string and n: number.

Example runs:

>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)
ans = 
    @(s,n)flip(repelem(s,abs(n)),(n<0)+1)

>> f = ans;

>> f('String', 3)
ans =
SSStttrrriiinnnggg

>> f('String', -3)
ans =
gggnnniiirrrtttSSS

>> f('String', 0)
ans =
   Empty matrix: 1-by-0
\$\endgroup\$
2
  • \$\begingroup\$ Choosing which dimension to flip along was way better than the mess I wrote 😛 +1. and I always forget repelem exists. \$\endgroup\$ Jul 11, 2017 at 22:16
  • \$\begingroup\$ @StewieGriffin Well, you could incorporate that in your answer too :-) (+1 already). I think there's no repelem in Octave, for now \$\endgroup\$
    – Luis Mendo
    Jul 11, 2017 at 22:19
3
\$\begingroup\$

Brain-Flak (Haskell), 202 192 bytes

(({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}

Try it online!

This is probably the worst possible language to do it in, but it's done. Thanks to @Wheatwizard for providing the Haskell interpreter, which allows mixed input formats. This would be about 150 bytes longer without it.

Explanation:

#Keep track of the first input (n)
(({})<

    #Push abs(n) (thanks WheatWizard!)
    (([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>[()])>()}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the original n back on
>)

#Push n >= 0
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}
\$\endgroup\$
2
  • \$\begingroup\$ You could use my 52 byte abs to save 2 bytes, you could also use the 50 byte -abs I gave you and increment instead of decrementing to save 6 bytes. \$\endgroup\$
    – Wheat Wizard
    Jul 12, 2017 at 19:57
  • 1
    \$\begingroup\$ Some friendly competition. \$\endgroup\$
    – Wheat Wizard
    Jul 12, 2017 at 20:13
3
\$\begingroup\$

C89 bytes

main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}

I saw Ben Perlin's version and wondered if you couldn't be shorter still and also have a full program; surely, atoi() and putchar() aren't that expensive in terms of bytes? Seems I was right!

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

Java (OpenJDK 8), 99 98 89 87 85 bytes

s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}

Try it online!

  • -2 bytes thanks to @Xanderhall
  • -2 bytes thanks to @Nevay
\$\endgroup\$
7
  • \$\begingroup\$ Ideas that don't work (way longer): reverse the string before, use a stream, \$\endgroup\$ Jul 12, 2017 at 9:49
  • 1
    \$\begingroup\$ Save 2 bytes with s[(n<0?-l-~i:i)/n] \$\endgroup\$
    – Xanderhall
    Jul 12, 2017 at 13:19
  • \$\begingroup\$ @Xanderhall Thanks! I've been looking for that one for so long my eyes bleed. I knew it was possible, I just messed everything up when implementing it. \$\endgroup\$ Jul 12, 2017 at 13:20
  • 1
    \$\begingroup\$ @user902383 Yes, it's mandatory. If they were optional, a lot of things would be unreadable. Also, my function is not a "single statement", but a for-loop, which encompass several statements. \$\endgroup\$ Jul 13, 2017 at 15:07
  • 1
    \$\begingroup\$ You can save 1 byte by incrementing i in the condition s->n->{for(int l=s.length*(n<0?-n:n),i=0;i++<l;)System.out.print(s[(n<0?i-l:i-1)/n]);}. Another byte can be saved by iterating from -l to 0 instead (s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}). \$\endgroup\$
    – Nevay
    Jul 13, 2017 at 22:58
3
\$\begingroup\$

C (gcc), 108 106 103 101 bytes

-2 bytes thanks to ceilingcat

e,p,j,d;f(s,i)char*s;{p=0,e=strlen(s);for(i*=d=i<0?p=e-1,e=-1:1;p^e;p+=d)for(j=i;j--;)putchar(s[p]);}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @ceilingcat Cheers! \$\endgroup\$
    – gastropner
    Apr 29, 2020 at 22:48
2
\$\begingroup\$

Octave, 49 bytes

@(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}

Try it online!

I will provide an explanation tomorrow.

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

Ruby, 59 +1 = 60 bytes

Uses -n flag.

n=eval$_
a=$<.read
a.reverse!if n<0
a.chars{|i|$><<i*n.abs}

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ eval$_ is shorter than $_.to_i by 1 byte. String#chars can also accept a block the same way String#each_char can. Finally, reverse the input before processing each character so you can print it directly instead (switching your flag to -n). All of this combines to become 55+1=56 bytes. \$\endgroup\$
    – Value Ink
    Jul 11, 2017 at 22:14
2
\$\begingroup\$

Charcoal, 16 bytes

Fθ¿‹η0F±Iη←ιFIηι

Try it online! Link is to verbose version of code. Explanation:

Fθ              For each character in the input string
  ¿‹η0          If the input number is less than zero
      F±Iη      Repeat the negation of the input number times
          ←ι    Print the character leftwards (i.e. reversed)
      FIη       Otherwise repeat the input number times
         ι      Print the character
\$\endgroup\$
2
\$\begingroup\$

CJam, 9 bytes

q~__*@e*%

Try it online!

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

Japt, 12 bytes

®pVaìr!+sVg

Try it online!

Explanation

Implicit input of string U and integer V.

®pVaÃ

Map (®) each letter of U (implicitly) to itself repeated (p) abs(V) (Va) times.

¬r

Turn the string into an array of chars (¬) and reduce (r) that with...

!+sVg

"!+".slice(sign(V)) - this either reduces with +a + b, or with !+b + a.
Thanks @Arnauld for the backwards-reduce idea!

\$\endgroup\$
1
  • \$\begingroup\$ I feel like £gY*Vg)pVa should lead to a shorter solution but my brain has shut down for the holidays so I can't quite figure it out. You may be able to do something with it, though. \$\endgroup\$
    – Shaggy
    Jul 12, 2017 at 7:06
2
\$\begingroup\$

05AB1E, 9 bytes

Based off Riley's approach.

SÂΛ@²Ä×J

Try it online!

Explanation

SÂΛ@²Ä×J   Arguments: s, n
S           Push s split into individual characters
 Â          Get a (without popping) and push a reversed
  Λ        n lower than 0 (true = 1, false = 0)
    @       Get value at that index in the stack
     ²Ä×J   Repeat each character abs(n) times and join
            Implicit output
\$\endgroup\$
2
\$\begingroup\$

WendyScript, 46 bytes

<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW  oolllleeHH

Try it online!

Explanation (Ungolfed):

let f => (s, x) {
  let n = ""
  for i : s
    for j : 0->x
      if x > 0 n += i
      else n = i + n
  ret n
}
\$\endgroup\$
2
\$\begingroup\$

Pyth, 13 11 bytes

*sm*.aQdz._

Try it!

-2 bytes thanks to @jacoblaw

explanation

*sm*.aQdz._   
  m     z     # map onto the input string (lambda var: d)
   *.aQd      # repeat the char d as often as the absolute value of the input number 
 s            # sum the list of strings into a single string
*        ._Q   # Multiply with the sign of the implicit input value: reverse for negative Q 

old approach, 13 bytes

_W<Q0sm*.aQdz

Try it!

\$\endgroup\$
1
  • \$\begingroup\$ you can save two bytes with this reversal logic \$\endgroup\$
    – jacoblaw
    Jul 12, 2017 at 23:25
2
\$\begingroup\$

Python 3, 68 bytes

h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Hello, and welcome to the site! Unfortunately, this answer is invalid right now, since it doesn't support Negative numbers. The challenge says: If the integer is negative, we use its absolute value in the first step, and then reverse the string. \$\endgroup\$
    – DJMcMayhem
    Jul 12, 2017 at 20:05
  • \$\begingroup\$ Thanks for fixing it! BTW, you could take two bytes off by removing the spaces after parenthesis ) \$\endgroup\$
    – DJMcMayhem
    Jul 12, 2017 at 20:34
  • \$\begingroup\$ Edited, thanks for the contribution \$\endgroup\$
    – Kavi
    Jul 14, 2017 at 16:39
  • \$\begingroup\$ n<0 else => n<0else \$\endgroup\$
    – Adalynn
    Jul 14, 2017 at 16:47
2
\$\begingroup\$

Excel VBA, 93 89 88 86 85 Bytes

Anonymous VBE immediate window function that takes input as string from cell [A1] and int from cell [B1] and outputs to the VBE immediate window

l=[Len(A1)]:For i=1To l:For j=1To[Abs(B1)]:?Mid([A1],IIf([B1]>0,i,l+1-i),1);:Next j,i

-4 bytes for abandoning [C1] as intermediate variable

-1 byte for adding a as intermediate variable

-2 bytes for replacing a with l, ([Len(A1)])

\$\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.