| Bytes | Lang | Time | Link |
|---|---|---|---|
| 001 | Uiua | 250427T170806Z | Joao-3 |
| 089 | Swift 6 | 250302T022306Z | macOSist |
| 106 | Tcl | 170715T001303Z | sergiol |
| 007 | Thunno 2 | 230623T170043Z | The Thon |
| 074 | R | 170711T220043Z | BLT |
| 010 | Japt P | 230106T174259Z | Shaggy |
| 061 | JavaScript Node.js | 230108T101957Z | l4m2 |
| 061 | ><> Fish | 230107T153253Z | mousetai |
| 050 | Raku | 230107T040542Z | Mark Ree |
| 069 | Elm | 230107T034623Z | DLosc |
| 080 | C gcc | 230106T180128Z | l4m2 |
| 007 | Vyxal | 230104T223049Z | emanresu |
| 101 | C gcc | 171209T084246Z | gastropn |
| 132 | Forth | 200420T234053Z | axwr |
| 103 | [C#] | 200419T204031Z | KaleSurf |
| 024 | Clojure | 171210T194959Z | NikoNyrh |
| 085 | Excel VBA | 170712T105237Z | Taylor R |
| 013 | Husk | 170802T010245Z | ბიმო |
| 076 | Retina | 170718T143445Z | ovs |
| 007 | Unwanted | 170718T141936Z | faso |
| 068 | Python 3 | 170712T200059Z | Kavi |
| 085 | Java OpenJDK 8 | 170712T092907Z | Olivier |
| 011 | Pyth | 170711T220157Z | KarlKast |
| 152 | C++ | 170713T042353Z | Zack Lee |
| 045 | vim | 170713T232839Z | Ray |
| 026 | Brainfuck | 170713T224110Z | Ray |
| 089 | C89 bytes | 170713T173234Z | mystery |
| 108 | C# | 170713T130857Z | TheLetha |
| 013 | J | 170712T130904Z | Tikkanz |
| 070 | C# | 170713T001051Z | ChrisA |
| 046 | WendyScript | 170712T230728Z | Felix Gu |
| 152 | BrainFlak BrainHack | 170712T201330Z | Wheat Wi |
| 089 | PowerShell | 170712T195506Z | Tessella |
| 192 | BrainFlak Haskell | 170712T193901Z | DJMcMayh |
| 017 | V | 170711T210529Z | DJMcMayh |
| 018 | K/Kona | 170712T154518Z | Simon Ma |
| 009 | 05AB1E | 170712T132555Z | kalsower |
| 065 | PHP>=7.1 | 170712T102707Z | Jör |
| 056 | Mathematica | 170712T112854Z | Not a tr |
| 012 | Japt | 170712T004209Z | Justin M |
| 036 | Haskell | 170711T220022Z | Laikoni |
| 009 | CJam | 170712T055158Z | Dennis |
| 044 | Julia | 170712T031943Z | Tanj |
| 109 | C | 170712T002920Z | Ben Perl |
| 016 | Charcoal | 170711T225345Z | Neil |
| nan | Ruby | 170711T220912Z | Pavel |
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)]}] ""}
Thunno 2, 7 bytes
AḄ$0<?r
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
Æ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
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
Explanation
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.
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
nis negative, callfon its absolute value (f -n); then compose (>>) the resulting function withList.reverse. - Else, create a function that puts
ncopies 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).
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)]);}
-1 byte from ceilingcat
Vyxal, 7 bytes
ȧ•?0<[Ṙ
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]);}
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);
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
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
\`^¶|
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
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]);}
- -2 bytes thanks to @Xanderhall
- -2 bytes thanks to @Nevay
Pyth, 13 11 bytes
*sm*.aQdz._
-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
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.
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-@>]
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
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
([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}
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('-')})
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
(({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}
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ñÓ./&ò
ÀäëÍî
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
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)];
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
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])
Example usage: f (-3) "abc" yields "cccbbbaaa".
Edit: -5 bytes thanks to xnor!
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
