g | x | w | all
Bytes Lang Time Link
001Uiua250427T170806ZJoao-3
089Swift 6250302T022306ZmacOSist
106Tcl170715T001303Zsergiol
007Thunno 2230623T170043ZThe Thon
074R170711T220043ZBLT
010Japt P230106T174259ZShaggy
061JavaScript Node.js230108T101957Zl4m2
061><> Fish230107T153253Zmousetai
050Raku230107T040542ZMark Ree
069Elm230107T034623ZDLosc
080C gcc230106T180128Zl4m2
007Vyxal230104T223049Zemanresu
101C gcc171209T084246Zgastropn
132Forth200420T234053Zaxwr
103[C#]200419T204031ZKaleSurf
024Clojure171210T194959ZNikoNyrh
085Excel VBA170712T105237ZTaylor R
013Husk170802T010245Zბიმო
076Retina170718T143445Zovs
007Unwanted170718T141936Zfaso
068Python 3170712T200059ZKavi
085Java OpenJDK 8170712T092907ZOlivier
011Pyth170711T220157ZKarlKast
152C++170713T042353ZZack Lee
045vim170713T232839ZRay
026Brainfuck170713T224110ZRay
089C89 bytes170713T173234Zmystery
108C#170713T130857ZTheLetha
013J170712T130904ZTikkanz
070C#170713T001051ZChrisA
046WendyScript170712T230728ZFelix Gu
152BrainFlak BrainHack170712T201330ZWheat Wi
089PowerShell170712T195506ZTessella
192BrainFlak Haskell170712T193901ZDJMcMayh
017V170711T210529ZDJMcMayh
018K/Kona170712T154518ZSimon Ma
00905AB1E170712T132555Zkalsower
065PHP>=7.1170712T102707ZJör
056Mathematica170712T112854ZNot a tr
012Japt170712T004209ZJustin M
036Haskell170711T220022ZLaikoni
009CJam170712T055158ZDennis
044Julia170712T031943ZTanj
109C170712T002920ZBen Perl
016Charcoal170711T225345ZNeil
nanRuby170711T220912ZPavel

Uiua, 1 byte

Yes. This problem is solved with a single glyph. Takes the number to multiply by on the top, and the string on the bottom. ▽ keep with a number on top of the stack repeats every character that many times, reversing for negatives.

I'm not going to even link to the pad, as this solution is so simple that I don't feel like it needs to be linked.

Swift 6, 102 89 bytes

let m={s,n in{n<0 ?""+$0.reversed():$0}((s+"").map{{String.init}()($0,abs(n))}.joined())}

Tcl, 106 bytes

proc M s\ n {join [lmap c [split [expr {$n<0?[string rev $s]:$s}] ""] {string repe $c [expr abs($n)]}] ""}

Try it online!

Thunno 2, 7 bytes

AḄ$0<?r

Attempt This Online!

Explanation

AḄ$0<?r  # Implicit input
 Ḅ       # Multiply each character of the second input by...
A        # ...the absolute value of the first input
  $      # Push the first input again
   0<    # And check if it's negative
     ?   # If it is negative:
      r  #  Reverse the string
         # Implicit output

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

Japt -P, 10 bytes

ÆVÃÕzUÌÉ©2

Try it

ÆVÃÕzUÌÉ©2     :Implicit input of integer U & string V
Æ              :Map the range [0,U)
 V             :  Return V
  Ã            :End map
   Õ           :Transpose
    z          :Rotate clockwise this many times
     UÌ        :  Sign of difference between U & -1
       É       :  Subtract 1
        ©2     :  Logical AND with 2
               :Implicitly join & output

JavaScript (Node.js), 61 bytes

n=>g=(h,i=n,[c,...x]=h)=>c?i?i>0?c+g(h,i-1):g(h,i+1)+c:g(x):h

Try it online!

No longer longer than Q256411, but even same length it's only

><> (Fish), 61 bytes

:&0)?v>i:0(?^\
-$0&0/\p3a'r'&
 .07~v?:<+1&:/
{:}+1/ >o< ~\.28

Try it

Explanation

enter image description here

Takes the number as the initial stack value, and the string as the STDIN.

Uses source code modification: Inserts a r command at 10,3 if the number is positive. If so invert the number. The & instruction is nicely in the perfect place both from the top and from the right side.

The {:} copies the character -n times.

Raku, 50 bytes

{($^a.comb »x»$^b.abs).join.&{$b <0??.flip!!$_}}

Try it online!

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:

C (gcc), 80 bytes

i;L;f(s,n)char*s;{L=strlen(s);for(i=0;i*i<L*n*L*n;)putchar(s[i++/n+~-L*(n<0)]);}

Try it online!

-1 byte from ceilingcat

Vyxal, 7 bytes

ȧ•?0<[Ṙ

Try it Online!

There's gotta be a better way to do this.

 •      # Repeat each char by...
ȧ       # absolute value of input
  ?0<[  # If it's negative
      Ṙ # Reverse

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!

Forth, 132 bytes.

My first golf, Idk what I'm doing I'm sure it could be improved a lot.

: Z chars + c@ emit ; : X 0 do dup n Z loop ; : Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

or

: Z chars + c@ emit ;
: X 0 do dup n Z loop ;
: Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

The negate and comparisons are just for the 0 and negative cases. This is assuming we've already been given the string at 'n', I'm unsure if this is allowed.

[C#], 103 bytes

var r=n<0?-n:n;var a=new int[p.Length*r].Select((_,i)=>p[i/r]);return String.Concat(n<0?a.Reverse():a);

Try It Online!

Tried something a little different from the other C# answers, without using 'new string(str, x)'.

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

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

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

Retina, 76 bytes

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

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

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

Try it online!

Unwanted, Unnecessary, Opportunistic, 7 bytes

IAM*|V^

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!

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!

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!

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

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

Brainfuck, 26 bytes

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

Try it online!

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!

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();
        }
    }
}

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

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.

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
}

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

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)

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

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.

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"

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

PHP>=7.1, 65 bytes

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

PHP Sandbox Online

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.

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!

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!

CJam, 9 bytes

q~__*@e*%

Try it online!

Julia, 44 bytes

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

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;

}

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

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!