Multiply a string by a number!

34

1

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!

Gryphon

Posted 2017-07-11T20:59:54.780

Reputation: 6 697

4Can we assume the string is printable ASCII-only, plus newlines? – mbomb007 – 2017-07-11T21:45:57.267

Can we output a list of strings? – totallyhuman – 2017-07-11T21:50:15.280

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. https://tio.run/##K0otycxL/P8/Tk@bS0WLqzhBw97G9tA2PS1NLk6u6oQ4Qy6uWohgnCFQkFNDDyihYqhiyBWTEHdoWw0n1///RlweqTk5@Vzh@UU5KYoA

– mbomb007 – 2017-07-11T21:59:26.153

@mbomb007, yes, sorry for taking so long about that. – Gryphon – 2017-08-02T00:08:13.717

@totallyhuman, no you may not. – Gryphon – 2017-08-08T03:52:35.180

Answers

31

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.

Dennis

Posted 2017-07-11T20:59:54.780

Reputation: 196 637

1OK, now I'm really impressed. I'd love an explanation of this particular wonder in miniature. – Gryphon – 2017-07-11T21:12:26.117

Sure. As soon as I made a test suite and am done golfing. – Dennis – 2017-07-11T21:18:46.170

4OK, if you can make this any smaller, I'm going to give up trying to make a question that will take you >10 bytes. – Gryphon – 2017-07-11T21:19:45.457

Woah. Never seen an input nilad being used before! – Zacharý – 2017-07-11T21:22:41.360

@Zacharý Rarely useful, but dyadic chain rules weren't doing what I wanted. – Dennis – 2017-07-11T21:24:10.693

@Gryphon Added an explanation. – Dennis – 2017-07-11T21:28:14.100

13OK, that's it. I'm learning Jelly. I want to be able to do magic too. – Gryphon – 2017-07-11T21:31:58.403

Wait ... how does x not think m is an argument? – Zacharý – 2017-07-11T21:34:41.560

@Zacharý In monadic chains, dyads don't bind to each other. That's why I'm using a nilad. – Dennis – 2017-07-11T21:35:38.377

So ... it sort of becomes post-fix because it has to? – Zacharý – 2017-07-11T21:36:48.950

@Zacharý That's how all chains work: process as many links as possible, skip them, start over. – Dennis – 2017-07-11T21:39:10.633

gives up I guess I'll have to learn Jelly. – Magic Octopus Urn – 2017-07-11T21:54:33.630

2We all know how a discussion about Jelly chains ends up being a mess... – Erik the Outgolfer – 2017-07-12T09:11:10.123

9

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!

totallyhuman

Posted 2017-07-11T20:59:54.780

Reputation: 15 378

9

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))

Arnauld

Posted 2017-07-11T20:59:54.780

Reputation: 111 334

3+1 for reduce! – Neil – 2017-07-11T22:46:55.733

9

Python 3, 44 bytes

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

Try it online!

Dennis

Posted 2017-07-11T20:59:54.780

Reputation: 196 637

The base case seems to ignore the last character. – xnor – 2017-07-11T21:45:23.457

Not quite sure why I did that... Thanks! – Dennis – 2017-07-11T21:46:28.000

141 bytes. but idk if a function call as f(n,*s) is considered valid – Felipe Nardi Batista – 2017-07-12T13:39:30.207

6

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

Riley

Posted 2017-07-11T20:59:54.780

Reputation: 11 345

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. – Magic Octopus Urn – 2017-07-11T21:17:55.917

@MagicOctopusUrn I've used something like ²0‹i before and I always think there has to be something better. – Riley – 2017-07-11T21:19:28.837

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. – Magic Octopus Urn – 2017-07-11T21:20:38.697

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.

– Magic Octopus Urn – 2017-07-11T21:53:00.647

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) – kalsowerus – 2017-07-12T08:15:05.043

@kalsowerus That's a completely different approach than mine. Feel free to post it yourself. – Riley – 2017-07-12T13:08:14.787

5

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.

James

Posted 2017-07-11T20:59:54.780

Reputation: 54 537

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.

– nmjcman101 – 2017-07-12T02:12:22.587

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. – Gryphon – 2017-07-12T13:51:49.417

@nmjcman101 Oh wow, that's so obvious, I don't know how I didn't think of it. Thank you! – James – 2017-07-12T16:47:28.590

@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 – James – 2017-07-12T16:48:04.200

5

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!

Laikoni

Posted 2017-07-11T20:59:54.780

Reputation: 23 676

1There's (<*[1..n]) for ((<$[1..n])=<<). – xnor – 2017-07-11T22:22:25.323

@xnor Thanks! That's good to know. – Laikoni – 2017-07-12T05:58:02.283

5

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!!

BLT

Posted 2017-07-11T20:59:54.780

Reputation: 931

2Well done ! You could save a few bytes by writing rep(foo,,,3) or rep(foo,e=3) (same lenght) ;-) – Frédéric – 2017-07-11T22:12:24.230

@Frédéric you beat me to it, I was going to say the same thing! – Giuseppe – 2017-07-11T22:13:19.493

-2 bytes – Giuseppe – 2017-07-11T22:19:04.100

actually, with Frederic's improvement, that gets you down to 78, which isn't too bad. – Giuseppe – 2017-07-11T22:21:32.510

Thanks! @Giuseppe, can you help me understand what your if statement is doing? – BLT – 2017-07-11T22:31:48.457

1yeah, 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. – Giuseppe – 2017-07-11T22:39:03.810

1

btw, the R docs for Paren say that ( is semantically equivalent to the identity function(x)x

– Giuseppe – 2017-07-12T20:24:56.500

176 bytes – Giuseppe – 2017-12-07T19:10:57.870

5

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)

Luis Mendo

Posted 2017-07-11T20:59:54.780

Reputation: 87 464

4

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

Emigna

Posted 2017-07-11T20:59:54.780

Reputation: 50 798

4

PHP>=7.1, 65 bytes

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

PHP Sandbox Online

Jörg Hülsermann

Posted 2017-07-11T20:59:54.780

Reputation: 13 026

1In integer context, $n<0 has the same value as $n<0?:0 but it's 3 bytes shorter :-) – axiac – 2017-07-12T12:01:26.727

4

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

Tikkanz

Posted 2017-07-11T20:59:54.780

Reputation: 191

2(#~|)A.~0-@>] for 13 bytes – miles – 2017-07-12T19:48:56.160

Very nice @miles ! – Tikkanz – 2017-07-12T20:20:51.483

No problem. You also don't need to count the parentheses used to invoke the verb. – miles – 2017-07-12T23:20:22.763

1Also 13 bytes: #~ ::(|.@#~|) – FrownyFrog – 2017-12-08T12:26:26.770

4

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
{}

Post Rock Garf Hunter

Posted 2017-07-11T20:59:54.780

Reputation: 55 382

3

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

Uriel

Posted 2017-07-11T20:59:54.780

Reputation: 11 708

Umm, it'd be nice if the TIO like worked? – Gryphon – 2017-07-11T21:02:53.947

@Gryphon and here goes the byte... – Uriel – 2017-07-11T21:06:04.233

Yep, I'd just realized that and was typing out my comment to tell you. – Gryphon – 2017-07-11T21:06:44.627

3

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

Luis Mendo

Posted 2017-07-11T20:59:54.780

Reputation: 87 464

Choosing which dimension to flip along was way better than the mess I wrote +1. and I always forget repelem exists. – Stewie Griffin – 2017-07-11T22:16:05.127

@StewieGriffin Well, you could incorporate that in your answer too :-) (+1 already). I think there's no repelem in Octave, for now – Luis Mendo – 2017-07-11T22:19:25.120

3

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

Olivier Grégoire

Posted 2017-07-11T20:59:54.780

Reputation: 10 647

Ideas that don't work (way longer): reverse the string before, use a stream, – Olivier Grégoire – 2017-07-12T09:49:49.377

1Save 2 bytes with s[(n<0?-l-~i:i)/n] – Xanderhall – 2017-07-12T13:19:12.657

@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. – Olivier Grégoire – 2017-07-12T13:20:52.577

as your function is single statement, do you need curly brackets? – user902383 – 2017-07-13T14:51:00.090

1

@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.

– Olivier Grégoire – 2017-07-13T15:07:45.477

1You 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]);}). – Nevay – 2017-07-13T22:58:43.423

@Nevay This is some really nice golfing. Thank you! – Olivier Grégoire – 2017-07-14T10:46:50.230

3

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
{}

James

Posted 2017-07-11T20:59:54.780

Reputation: 54 537

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. – Post Rock Garf Hunter – 2017-07-12T19:57:34.347

1Some friendly competition. – Post Rock Garf Hunter – 2017-07-12T20:13:56.650

2

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.

Stewie Griffin

Posted 2017-07-11T20:59:54.780

Reputation: 43 471

2

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!

KarlKastor

Posted 2017-07-11T20:59:54.780

Reputation: 2 352

you can save two bytes with this reversal logic

– jacoblaw – 2017-07-12T23:25:04.543

2

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!

Pavel

Posted 2017-07-11T20:59:54.780

Reputation: 8 585

1eval$_ 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. – Value Ink – 2017-07-11T22:14:26.290

2

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

Neil

Posted 2017-07-11T20:59:54.780

Reputation: 95 035

2

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!

Justin Mariner

Posted 2017-07-11T20:59:54.780

Reputation: 4 746

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. – Shaggy – 2017-07-12T07:06:16.017

2

CJam, 9 bytes

q~__*@e*%

Try it online!

Dennis

Posted 2017-07-11T20:59:54.780

Reputation: 196 637

2

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!

Kavi

Posted 2017-07-11T20:59:54.780

Reputation: 31

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.

– James – 2017-07-12T20:05:55.763

Thanks for fixing it! BTW, you could take two bytes off by removing the spaces after parenthesis ) – James – 2017-07-12T20:34:13.020

Edited, thanks for the contribution – Kavi – 2017-07-14T16:39:32.273

n<0 else => n<0else – Zacharý – 2017-07-14T16:47:59.037

2

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
}

Felix Guo

Posted 2017-07-11T20:59:54.780

Reputation: 211

2

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!

Andrea

Posted 2017-07-11T20:59:54.780

Reputation: 318

1

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]

J42161217

Posted 2017-07-11T20:59:54.780

Reputation: 15 931

1

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

steenbergh

Posted 2017-07-11T20:59:54.780

Reputation: 7 772

1

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

Skidsdev

Posted 2017-07-11T20:59:54.780

Reputation: 9 656

1

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;

}

Ben Perlin

Posted 2017-07-11T20:59:54.780

Reputation: 69

This does not seem to work for negative n. – gastropner – 2017-12-08T10:43:07.920

1

Julia, 44 bytes

(s,x)->for i in split(s,"") print(i^abs(x))end

Tanj

Posted 2017-07-11T20:59:54.780

Reputation: 199

That doesn't quite work. When the integer argument is negative, the string should be reversed. – Dennis – 2017-07-12T14:39:53.187

1

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)])

Taylor Scott

Posted 2017-07-11T20:59:54.780

Reputation: 6 709

1

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

kalsowerus

Posted 2017-07-11T20:59:54.780

Reputation: 1 894

1

K/Kona, 19 18 bytes

{,/$[y>0;;|:]y#'x}

Now, in the 0 case, it does output something, but that's the empty string so I'm sure that's all gravy.

I actually missed the negative input part of this initially, which cost me eleven bytes! Definitely not my best work

Usage:

k){,/$[y>0;;|:]y#'x}["Hello World";3]
"HHHeeellllllooo   WWWooorrrlllddd!!!"
k){,/$[y>0;;|:]y#'x}["Hello World!";0]
""
k){,/$[y>0;;|:]y#'x}["String";-3]
"gggnnniiirrrtttSSS"

Simon Major

Posted 2017-07-11T20:59:54.780

Reputation: 401

1

PowerShell, 89 bytes

param($s,$n)-join($s[((0..($L=$s.Length)),(-1..-$L))[$n[0]-eq45]]|%{"$_"*"$n".trim('-')})

Try it online!

Generates a list of characters in the string, either forward or reversed, string-multiplies each, and joins the resulting array. $n[0]-eq45 is the ASCII code of - and .Trim('-') is shorter than [Math]::Abs($n)

TessellatingHeckler

Posted 2017-07-11T20:59:54.780

Reputation: 2 412

1

C++, 152 bytes

#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

And here's the full code you can test with.

#include <iostream>

#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

int main(int argc, const char * argv[]) {
    std::cout << f("Hello World!", 3) << std::endl;
    std::cout << f("foo", 12) << std::endl;
    std::cout << f("String", -3) << std::endl;
    std::cout << f("This is a fun challenge", 0) << std::endl;
    std::cout << f("Hello\nWorld!", 2) << std::endl;
    return 0;
}

Zack Lee

Posted 2017-07-11T20:59:54.780

Reputation: 121

To start you certainly don't need all the whitespace here. – Post Rock Garf Hunter – 2017-07-13T05:06:03.263

@WheatWizard Thanks! I didn't know the spaces don't count. – Zack Lee – 2017-07-13T14:34:41.200

I'm not getting the same byte count. I'm getting 202 bytes. If I remove all the unnecessary whitespace it goes down to 140, but I don't see where the 134 number is coming from. – Post Rock Garf Hunter – 2017-07-13T14:37:55.203

1@ZackLee Spaces do count. You can just remove a lot of them by writing the whole thing on one line and writing (for example) for( instead of for ( – F1Krazy – 2017-07-13T15:00:23.187

You need to count those typedefs and defines. And the #include. And the using nam...you need to count everything that isn't main. – Ray – 2017-07-13T22:44:01.773

@Ray Thanks! I updated my code. I didn't count "#include <iostream>" as it is a default library for C++. – Zack Lee – 2017-07-14T04:33:03.387

1

Brainfuck, 26 bytes

,>>,[<<[->+>.<<]>[-<+>]>,]

Try it online!

Ray

Posted 2017-07-11T20:59:54.780

Reputation: 1 488

1

vim, 45 bytes

:s/\(.\)/\1<C-v>
/g
adl<esc>gJaP<esc>"add
:%norm @a
:%j!

<esc> is 0x1b, and <C-v> is 0x16.

:s/\(.\)/\1<C-v><nl>/g splits the string into one character per line.

adl<esc>gJaP<esc>"add then constructs a command in buffer a that will copy a line n times, where n is the number that was previously on this line.

%norm @a and :%j! then apply that command to each line in the file and rejoin the lines respectively.

Try it online

Ray

Posted 2017-07-11T20:59:54.780

Reputation: 1 488

1

faso

Posted 2017-07-11T20:59:54.780

Reputation: 141

1

C, 108 106 bytes

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

gastropner

Posted 2017-07-11T20:59:54.780

Reputation: 3 264

0

Mathematica, 56 bytes

""<>Thread@Table[Reverse[Characters@#2,2+Sign@#],Abs@#]&

Try it at the Wolfram sandbox! (Doesn't work in Mathics…)

Takes the number then the string as input.

The Reverse function can take a second parameter saying what level of the array to reverse at (so Reverse[{{1,2},{3,4}}] returns {{3,4},{1,2}} but Reverse[{{1,2},{3,4}},2] gives {{2,1},{4,3}}, for instance). When the input number is negative, we reverse at level 1, but when it's zero or positive, we reverse at level 2 or 3. Since Characters@#2 is a list with only one level, reversing at deeper levels has no effect.

Once that's done, we repeat the list of characters then transpose the resulting array using Thread so the repeated characters end up next to each other.

Not a tree

Posted 2017-07-11T20:59:54.780

Reputation: 3 106

0

C#, 70 Bytes

using System.Linq;(s,n)=>string.Join("",s.Select(c=>new string(c,n)));

The select function is used to create a new string with the original character repeated n-times, results are joined together.

ChrisA

Posted 2017-07-11T20:59:54.780

Reputation: 1

Hello and Welcome to PPCG! Unfortunatley your answer does not work for negatives or zero. You can also shorten your code by using currying i.e. s=>n=>, string.Concat() and you don't need the trailing semi colon. – TheLethalCoder – 2017-07-13T13:00:57.997

0

C#, 108 bytes

using System.Linq;s=>n=>{var a=s.Select(c=>new string(c,n>0?n:-n));return string.Concat(n<0?a.Reverse():a);}

Full/Formatted Version:

using System;
using System.Linq;

namespace TestBed
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, Func<int, string>> f = s => n =>
            {
                var a = s.Select(c => new string(c, n > 0 ? n : -n));

                return string.Concat(n < 0 ? a.Reverse() : a);
            };

            Console.WriteLine(f("Hello World!")(3));
            Console.WriteLine(f("foo")(12));
            Console.WriteLine(f("String")(-3));
            Console.WriteLine(f("This is a fun challenge")(0));
            Console.WriteLine(f(@"Hello
World!")(2));

            Console.ReadLine();
        }
    }
}

TheLethalCoder

Posted 2017-07-11T20:59:54.780

Reputation: 6 930

0

tcl, 120

proc M s\ n {if $n<0 {set s [string rev $s];set n [expr -$n]};lmap c [split $s ""] {append x [string repe $c $n]};set x}

demo

sergiol

Posted 2017-07-11T20:59:54.780

Reputation: 3 055

0

Retina, 76 bytes

Os^$`(?<=^-.+¶.*).

^.+
$*
s`(?<=¶.*)
	
{`^1

}s`(?<=^1.*)	(.)
	$1$1
\`^¶|	

Try it online!

ovs

Posted 2017-07-11T20:59:54.780

Reputation: 21 408

0

Husk, 13 bytes

So?I↔>0o`ȯṁRa

Try it online!

Ungolfed/Explanation

       o`ȯṁ    -- with the input string..
           Ra  -- ..multiply each character by the absolute value |N|
So?            -- depending on N either apply..
   I           -- ..the identity..
     >0        -- ..if N>0 or else..
    ↔          -- ..reverse it

ბიმო

Posted 2017-07-11T20:59:54.780

Reputation: 15 345

0

Clojure, 24 bytes

#(for[c % _(range %2)]c)

Returning a string instead of a sequence of characters pushes this to 35 bytes:

#(apply str(for[c % _(range %2)]c))

NikoNyrh

Posted 2017-07-11T20:59:54.780

Reputation: 2 361