# StringgnirtSStringgnirtSStringgnirtS

Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

Hello!

You should output:

Hello!!olleHHello!!olleHHello!!olleH

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

Hello!
!olleH
Hello!
!olleH
Hello!
!olleH

This would not be a valid solution!

Here are some more test cases:

Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224

Since this is a challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

1. The shortest answer out of all languages, and

2. The shortest answer in each individual language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

• In your example, shouldn't that be olleH, not elloH ? – Arnaud Sep 15 '16 at 3:27
• @Downgoat No, you must take input and output in the same format as the spec describes. – DJMcMayhem Sep 15 '16 at 4:15
• Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? – Luis Mendo Sep 15 '16 at 8:39
• @carusocomputing It won't: "You can safely assume that the input string will not be empty, and will only contain printable ASCII." – Martin Ender Sep 15 '16 at 13:50
• en.wikipedia.org/wiki/ASCII#Printable_characters Ah, didn't know that was a well defined subset of ASCII. I imagined printable to include \t, \n, etc... – Magic Octopus Urn Sep 15 '16 at 14:59

# Wren, 39 bytes

Beats Python by 1 byte.

Fn.new{|n|(n=n[-1..0]).map{n=n[-1..0]}}

Try it online!

## Explanation

Fn.new{|n|                            } // Anonymous function with n
(n=n[-1..0])                  // Step 1. Set n as the reverse of n
// Before the mapping of every item
// in this list. Why? Because the
// initialization in the map function
// is done *before* the value is returned.

.map{          }  // Step 2. Map every item in this list
n=n[-1..0]   // to the current state of this string
// reversed.
$$`$$

->s{s.each_char{$><<s;s.reverse!}} Try it online! This goes through each character of the string (a loop that runs as many times as the length of the string) and prints the string, and then reverses it.$><<s is a golfed version of print s. It appends (<<) the value (s) to stdout ($>). # Java 8 bytecode, 412 bytes (403 bytes + -noverify) Hexdump because it's unprintables all the way down: 00000000: cafe babe 0003 002d 0020 0a00 0c00 040c .......-. ...... 00000010: 0017 001f 0100 1628 5b4c 6a61 7661 2f6c .......([Ljava/l 00000020: 616e 672f 5374 7269 6e67 3b29 560c 000e ang/String;)V... 00000030: 0010 0100 063c 696e 6974 3e07 0011 0100 .....<init>..... 00000040: 0570 7269 6e74 0100 066c 656e 6774 6807 .print...length. 00000050: 0015 0100 0443 6f64 6501 0004 6d61 696e .....Code...main 00000060: 0700 1609 0009 0002 0100 0772 6576 6572 ...........rever 00000070: 7365 0100 0a53 6f75 7263 6546 696c 6501 se...SourceFile. 00000080: 001a 2829 4c6a 6176 612f 6c61 6e67 2f53 ..()Ljava/lang/S 00000090: 7472 696e 6742 7566 6665 723b 0100 136a tringBuffer;...j 000000a0: 6176 612f 696f 2f50 7269 6e74 5374 7265 ava/io/PrintStre 000000b0: 616d 0100 0328 2949 0a00 0600 140c 0007 am...()I........ 000000c0: 001c 0100 106a 6176 612f 6c61 6e67 2f53 .....java/lang/S 000000d0: 7973 7465 6d01 0016 6a61 7661 2f6c 616e ystem...java/lan 000000e0: 672f 5374 7269 6e67 4275 6666 6572 0100 g/StringBuffer.. 000000f0: 036f 7574 0a00 0c00 1d07 000a 0c00 0500 .out............ 00000100: 1c0a 000c 001a 0100 1528 4c6a 6176 612f .........(Ljava/ 00000110: 6c61 6e67 2f53 7472 696e 673b 2956 0c00 lang/String;)V.. 00000120: 0800 1201 0000 0100 154c 6a61 7661 2f69 .........Ljava/i 00000130: 6f2f 5072 696e 7453 7472 6561 6d3b 0020 o/PrintStream;. 00000140: 0019 0006 0000 0000 0001 0009 000b 0003 ................ 00000150: 0001 000a 0000 0031 0004 0001 0000 0025 .......1.......% 00000160: bb00 0c59 2a03 32b7 001b 59b6 0018 3b59 ...Y*.2...Y...;Y 00000170: b200 0d5f b600 13b6 0001 c484 0000 ffff ..._............ 00000180: 1a9a ffee b100 0000 0000 0100 0f00 0000 ................ 00000190: 0200 1e Jasmin assembly code: .source "" .class Code .super java/io/PrintStream .method public static main([Ljava/lang/String;)V .limit stack 4 .limit locals 1 new java/lang/StringBuffer dup aload_0 iconst_0 aaload invokenonvirtual java/lang/StringBuffer/<init>(Ljava/lang/String;)V dup invokevirtual java/lang/StringBuffer/length()I istore_0 Loop: dup getstatic java/lang/System/out Ljava/io/PrintStream; swap invokevirtual java/io/PrintStream/print(Ljava/lang/String;)V invokevirtual java/lang/StringBuffer/reverse()Ljava/lang/StringBuffer; iinc 0 -1 iload_0 ifne Loop return .end method What CFR thinks this decompiles to (it's actually mostly correct this time): /* * Decompiled with CFR 0.148. */ import java.io.PrintStream; class Code extends PrintStream { public static void main(String[] arrstring) { StringBuffer stringBuffer = new StringBuffer(arrstring[0]); StringBuffer stringBuffer2 = stringBuffer; int n = stringBuffer.length(); do { System.out.print((String)((Object)stringBuffer2)); stringBuffer2 = stringBuffer2.reverse(); } while (--n != 0); } } Needs -noverify because the JVM will just kinda cast it anyways, allowing me to save on needing the (Ljava/lang/Object;)V descriptor # Ruby, 43 bytes f=->s,i=s.size{$><<s
i<2||f[s.reverse,i-1]}

See it on eval.in: https://eval.in/642616

## Actually, 12 bytes

;;l)Rkp;)αHΣ

Try it online!

Explanation:

;;l)Rkp;)αHΣ
;;l           dupe string twice, use one copy to get length (call it L)
)          move length to bottom of stack
R         reverse one copy of string
k        pop entire stack and push as list
p       pop L from list
;)     dupe L, move one copy to bottom
α    repeat each element (the forward and reversed string) of the list L times
H   first L elements in list (trim off excess elements)
Σ  concatenate

# Groovy, 51 bytes

def d(s){s.size().times{print(it%2?s.reverse():s)}}
• Anonymous function/proc/lambda/closure/whatever each language may call them, are also acceptable: {s->s.each{print(s);s=s.reverse()}}. – manatwork Sep 15 '16 at 8:19
• you should post that as your own solution. this is much better than my version! you significantly improved it, so you should earn the groovy trophy for this! – norganos Sep 15 '16 at 8:36

## C#, 137 bytes

void S(string i){Console.WriteLine(string.Join("",i.Select((c,n)=>(n%2==0)?i:i.Reverse()).Select(x=>new string(x.ToArray())).ToList()));}

Ungolfed:

void S(string i)
{
Console.WriteLine(string.Join("",
i.Select((c, n) => (n%2 == 0) ? i : i.Reverse()).Select(x => new
string(x.ToArray())).ToList()));
}
• All the usings are missing in this answer: those would add another 31 bytes. – Scepheo Sep 15 '16 at 8:59
• Since no-one said it yet, welcome to PPCG! – Erik the Outgolfer Sep 15 '16 at 11:39

# Java, 68 bytes

b->s->{for(int i=b.reverse().length();i-->0;)s.append(b.reverse());}

Or if the 2nd argument isn't allowed, 79 bytes:

b->{String s="";for(int i=b.reverse().length();i-->0;)s+=b.reverse();return s;}

## Testing and ungolfed

import java.util.function.BiConsumer;
import java.util.function.Function;

public class Main {

public static void main(String[] args) {

// Shortest version
BiConsumer<StringBuilder, StringBuilder> f = (in, out) -> {
in.reverse();
for (int i = in.length(); i-- > 0;) {
out.append(in.reverse());
}
};
// Longer version
Function<StringBuilder, String> g = in -> {
String out = "";
in.reverse();
for(int i = in.length(); i-->0; ) {
out+=in.reverse();
}
return out;
};

test(f, "Hello!");
System.out.println(g.apply(new StringBuilder("Hello!")));
}

static void test(BiConsumer<StringBuilder,StringBuilder> f, String txt) {
StringBuilder result = new StringBuilder();
f.accept(new StringBuilder(txt), result);
System.out.println(result);
}
}

# Swift 2.2 127 bytes

let x={(s:String) in var b = "";for var i in 1...s.characters.count {b += i%2==1 ?s:String(s.characters.reverse());};print(b);}

### unGolfed

let x={(s:String) in
var b = "";
for var i in 1...s.characters.count {
b += i%2==1 ?s:String(s.characters.reverse());
};
print(b);
}
• {s in print((0..<s.characters.count).map{$0%2==0 ?s:String(s.characters.reverse())}.joinWithSeparator(""))} – Lotte Tortorella Sep 17 '16 at 11:15 # PHP, 54 bytes while($c++-strlen($s=$argv[1]))echo$c%2?$s:strrev($s); I thought of this one myself before looking at other people's answers and then realised it's pretty much a combination of Crypto's and Titus' solutions... Well, I wanted to post it anyway :-) # Lua 5.1, 70 Bytes function f(s)return(s..s:reverse()):rep(#s/2)..(#s%2==1 and s or"")end Had odd numbers not been possible, I could have done it in 48 bytes by sheering off the ..(#s%2==1 and s or""), but the test cases prevented that. This was the shortest of three methods I tried, the others being. function f(s)local o return s:gsub(".",function()o=~o return o and s or s:reverse()end)end and function f(s)local o,t t=""for _ in s:gmatch(".")do o,t=~o,t..(o and s:reverse()or s)end return t end the locals were added in those two examples, for confidence that this function would always work. • 1. This doesn't work on odd numbers, because rep only takes integers (use // instead). 2. You can make up for the byte lost by that by switching the and..or around. – Scepheo Sep 15 '16 at 12:32 • Which version of Lua? Your gsub() solution not works with Lua 5.1.5 (“unexpected symbol near '~'”) and Lua 5.3.1 (“attempt to perform bitwise operation on a nil value (upvalue 'o')”). So no idea what you are doing in that callback function, but this way looks shorter: function(s)return s:gsub(".",function()o=s;s=s:reverse();return o end)end. – manatwork Sep 15 '16 at 12:35 • Only the top code is my submitted solution, function f(s)return(s..s:reverse()):rep(#s/2)..(#s%2==1 and s or"")end, secondly, :rep floors the value, and the ..(#%2==1 and s or"") accounts for odd numbers. – ATaco Sep 16 '16 at 0:55 # VBScript, 88 bytes a=WScript.Arguments(0) For i=1 To Len(a) WScript.StdOut.Write a a=StrReverse(a) Next Note: This does require the script execute using cscript.exe. For example... cscript.exe rev.vbs Hello! # Python 3, 8470 67 characters def s(d,i=1): t=d[::(i%2)*2-1] if i<len(d):t+=s(d,i+1) return t • You can insert r+=... to the same line as the for loop. – Yytsi Sep 18 '16 at 15:32 • (i%2)*4-1 is the same as i*2%4-1. – Post Rock Garf Hunter Sep 19 '16 at 1:40 • Try s=lambda d,i=0:d[::1-i*2%4]+s(d,i+1)if d[i:]else"" – Post Rock Garf Hunter Sep 19 '16 at 2:42 • You could also do s=lambda d,i=0:d+s(d[::-1],i+1)if d[i:]else"" but that really changes the algorithm. – Post Rock Garf Hunter Sep 19 '16 at 2:52 # Implicit, 10 bytes '¯^(]%\[´ö Try it online! Explanation: '¯^(]%\[´ö ' « read string »; ¯ « copy to memory »; ^ « push string length »; (...... « infinite loop »; ] « pull string to stack »; % « print string »; \ « reverse it »; [ « put it back in memory »; ´ « decrement string length »; ö « exit w/o implicit output if top of stack falsy, shortcut for )& »; ## ES7, 60 bytes b=>{for(c=b,d=0;d++<b.length;)c+=d%2?b:b.reverse();return c} # APL(NARS), 23 chars, 46 bytes {⍵{⍵≤1:⍺⋄⍺,(⌽⍺)∇⍵-1}≢⍵} test: f←{⍵{⍵≤1:⍺⋄⍺,(⌽⍺)∇⍵-1}≢⍵} f ,'a' a f 'Hello!' Hello!!olleHHello!!olleHHello!!olleH f 'abcd' abcddcbaabcddcba f 'OK!' OK!!KOOK! # Red, 43 bytes func[s][foreach c s[prin copy s reverse s]] Try it online! # Factor, 62 bytes : f ( x -- x ) [ length ] keep [ dup write reverse ] repeat ; Try it online! # PicoLisp, 70 bytes (de f(s)(for n(size s)(prin(if(= 1(% n 2))s(pack(reverse(chop s))))))) Try it online! # Gaia, 10 bytes :l┅r¦iv?¦$

Try it online!

:		| duplicate input
l		| take length
┅		| push range 1,2,3,...l
r¦		| modulo 2 1,0,1,...l%%2
iv?¦	| if truthy, push same, else push reverse

Try it online!

# Lua, 62 bytes

a=arg[1]for i=1,#a do io.write(i%2==1 and a or a:reverse())end

Try it online!

Full program, take input as argument.

# Kotlin, 67 bytes

{s->Array(s.length){if(it%2>0)s.reversed()else s}.joinToString("")}
• Initialize an array of s.length elements.
• Choose direction based on index
• Concat it all together

Try it online!

# Julia 1.0, 35 bytes

s->for _=s print(s);s=reverse(s)end

Try it online!

Loops over the input string characters and each iteration prints and reverses the string.

# C++ (gcc), 91 bytes

void f(string s){ for(int i = 0; i++ < s.size(); reverse(s.begin(), s.end())) cout << s;  }

Try it online!

• You could remove those abundant whitespace... But how are you able to use string functions and cout without including them in your code? – a'_' Dec 4 '19 at 13:36

# Zsh, 46 41 bytes

repeat $#1 s+=$1${(j::)${(Oas::)1}}
<<<$s${(Oas::)1}
${ 1} # take first parameter ( s::) # split into characters (Oa ) # reverse order${(j::)           }   # join