34
\$\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\$
  • 4
    \$\begingroup\$ Can we assume the string is printable ASCII-only, plus newlines? \$\endgroup\$ – mbomb007 Jul 11 '17 at 21:45
  • \$\begingroup\$ Can we output a list of strings? \$\endgroup\$ – totallyhuman Jul 11 '17 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 '17 at 21:59
  • \$\begingroup\$ @mbomb007, yes, sorry for taking so long about that. \$\endgroup\$ – Gryphon Aug 2 '17 at 0:08
  • \$\begingroup\$ @totallyhuman, no you may not. \$\endgroup\$ – Gryphon Aug 8 '17 at 3:52

47 Answers 47

31
\$\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\$
  • 1
    \$\begingroup\$ OK, now I'm really impressed. I'd love an explanation of this particular wonder in miniature. \$\endgroup\$ – Gryphon Jul 11 '17 at 21:12
  • \$\begingroup\$ Sure. As soon as I made a test suite and am done golfing. \$\endgroup\$ – Dennis Jul 11 '17 at 21:18
  • 4
    \$\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 '17 at 21:19
  • 13
    \$\begingroup\$ OK, that's it. I'm learning Jelly. I want to be able to do magic too. \$\endgroup\$ – Gryphon Jul 11 '17 at 21:31
  • 2
    \$\begingroup\$ We all know how a discussion about Jelly chains ends up being a mess... \$\endgroup\$ – Erik the Outgolfer Jul 12 '17 at 9:11
9
\$\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\$
  • 3
    \$\begingroup\$ +1 for reduce! \$\endgroup\$ – Neil Jul 11 '17 at 22:46
9
\$\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\$
  • \$\begingroup\$ The base case seems to ignore the last character. \$\endgroup\$ – xnor Jul 11 '17 at 21:45
  • \$\begingroup\$ Not quite sure why I did that... Thanks! \$\endgroup\$ – Dennis Jul 11 '17 at 21:46
  • 1
    \$\begingroup\$ 41 bytes. but idk if a function call as f(n,*s) is considered valid \$\endgroup\$ – Felipe Nardi Batista Jul 12 '17 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\$
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\$
  • \$\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\$ – Magic Octopus Urn Jul 11 '17 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 '17 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\$ – Magic Octopus Urn Jul 11 '17 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\$ – Magic Octopus Urn Jul 11 '17 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 '17 at 8:15
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\$
  • 1
    \$\begingroup\$ There's (<*[1..n]) for ((<$[1..n])=<<). \$\endgroup\$ – xnor Jul 11 '17 at 22:22
  • \$\begingroup\$ @xnor Thanks! That's good to know. \$\endgroup\$ – Laikoni Jul 12 '17 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\$
  • \$\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 '17 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 '17 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 '17 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 '17 at 16:48
5
\$\begingroup\$

R, 83 78 76 bytes

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

Anonymous function.

Frederic saved 3 bytes, Giuseppe saved 2 4.

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
                 `(`                       # otherwise leave it alone: `(` 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\$
  • 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 '17 at 22:12
  • \$\begingroup\$ @Frédéric you beat me to it, I was going to say the same thing! \$\endgroup\$ – Giuseppe Jul 11 '17 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 '17 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 '17 at 20:24
  • 1
    \$\begingroup\$ 76 bytes \$\endgroup\$ – Giuseppe Dec 7 '17 at 19:10
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
    \$\begingroup\$ In integer context, $n<0 has the same value as $n<0?:0 but it's 3 bytes shorter :-) \$\endgroup\$ – axiac Jul 12 '17 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
\$\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\$
  • 2
    \$\begingroup\$ (#~|)A.~0-@>] for 13 bytes \$\endgroup\$ – miles Jul 12 '17 at 19:48
  • \$\begingroup\$ Very nice @miles ! \$\endgroup\$ – Tikkanz Jul 12 '17 at 20:20
  • \$\begingroup\$ No problem. You also don't need to count the parentheses used to invoke the verb. \$\endgroup\$ – miles Jul 12 '17 at 23:20
  • 1
    \$\begingroup\$ Also 13 bytes: #~ ::(|.@#~|) \$\endgroup\$ – FrownyFrog Dec 8 '17 at 12:26
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\$
  • \$\begingroup\$ Umm, it'd be nice if the TIO like worked? \$\endgroup\$ – Gryphon Jul 11 '17 at 21:02
  • \$\begingroup\$ @Gryphon and here goes the byte... \$\endgroup\$ – Uriel Jul 11 '17 at 21:06
  • \$\begingroup\$ Yep, I'd just realized that and was typing out my comment to tell you. \$\endgroup\$ – Gryphon Jul 11 '17 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\$
  • \$\begingroup\$ Choosing which dimension to flip along was way better than the mess I wrote 😛 +1. and I always forget repelem exists. \$\endgroup\$ – Stewie Griffin Jul 11 '17 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 '17 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\$
  • \$\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\$ – Sriotchilism O'Zaic Jul 12 '17 at 19:57
  • 1
    \$\begingroup\$ Some friendly competition. \$\endgroup\$ – Sriotchilism O'Zaic Jul 12 '17 at 20:13
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\$
  • \$\begingroup\$ Ideas that don't work (way longer): reverse the string before, use a stream, \$\endgroup\$ – Olivier Grégoire Jul 12 '17 at 9:49
  • 1
    \$\begingroup\$ Save 2 bytes with s[(n<0?-l-~i:i)/n] \$\endgroup\$ – Xanderhall Jul 12 '17 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\$ – Olivier Grégoire Jul 12 '17 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\$ – Olivier Grégoire Jul 13 '17 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 '17 at 22:58
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
    \$\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 '17 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\$
  • \$\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 '17 at 7:06
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\$

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\$
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\$
  • \$\begingroup\$ you can save two bytes with this reversal logic \$\endgroup\$ – jacoblaw Jul 12 '17 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\$
  • \$\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 '17 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 '17 at 20:34
  • \$\begingroup\$ Edited, thanks for the contribution \$\endgroup\$ – Kavi Jul 14 '17 at 16:39
  • \$\begingroup\$ n<0 else => n<0else \$\endgroup\$ – Zacharý Jul 14 '17 at 16:47
1
\$\begingroup\$

QBIC, 32 bytes

g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';

Explanation

            Takes inputs A$ ('Hello'), and c (-3) from the cmd line
g=sgn(c)    Save the sign of c          -1
[_l;||      FOR each char in A$
[:*g|       FOR the number of repetitions wanted    (ie: -3 * -1)
            Note that : reads a number from the cmd line, and c is the first 
            available variable to save it in after a and b got used as FOR counters.
            Also note that a negative value times the sign becomes positive.
?_s         PRINT a substring
  A         of A$
 ,b*g       startng at char n, where n is the first FOR loop counter times the sign
                That means that when c is negative, so is this. A negative starting index
                on Substring instructs QBIC to take from the right.
 ,1|        taking 1 char.
';          This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 89 bytes

(T=Table;t=""<>T[s[[i]]~T~Abs@#2,{i,Length[s=Characters@#]}];If[#2>0,t,StringReverse@t])&


input

["Hello World!", 3]

\$\endgroup\$
1
\$\begingroup\$

Braingolf, 22 bytes

1-v{R.[v.R]v}R[v>R]v&@

Try it online!

Eeh, not bad.

Takes input as an integer and an array of characters.

Alternatively:

Braingolf, 31 bytes

l1->[M]1-v&,{R.[v.R]v}R[v>R]v&@

Try it online!

Takes input as an integer and a string

\$\endgroup\$
1
\$\begingroup\$

C, 109 bytes

char *f(int n, char *s){char *o=calloc(n,strlen(s)+1),*t=o;while(*s){for(int i=n;i--;)*t++=*s;s++;}return o;}

Starting with a function declaration that takes an int and a string and produces a string (it seems implied that memory is not preallocated and must be created) it seems that the straight-forward approach is shorter than any attempts at being cleaver that I had tried.

char *f(int n, char *s){
  char *o=calloc(n, strlen(s)+1),
    *t=o;

  while (*s) {
    for(int i=n; i--; )
      *t++=*s;
    s++;
  }

 return o;

}

\$\endgroup\$
  • \$\begingroup\$ This does not seem to work for negative n. \$\endgroup\$ – gastropner Dec 8 '17 at 10:43

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.