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

# 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


var QUESTION_ID=93261,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• In your example, shouldn't that be olleH, not elloH ? Sep 15 '16 at 3:27
• @Downgoat No, you must take input and output in the same format as the spec describes. Sep 15 '16 at 4:15
• Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? 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." 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... 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 ($>). • You can use the chars function instead of each_char – Jo King Jun 17 at 6:38 # 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 # 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  # Java (JDK), 68 bytes s->{var r=""+s;for(int i=s.length();i-->1;)r+=s.reverse();return r;}  Try it online! # Vyxal, 4 bytes (:₴Ṙ  Try it Online! I was looking through old Keg answers of mine and saw that I could improve on my score here with its improvement language. ## Explained (:₴Ṙ ( # for each character in the input: :₴ # print the top of the stack without a newline, preserving it. For the first iteration, this will be the original input. Ṙ # reverse the top of the stack. This achieves the string reversing effect, as it alternates the direction of the string each iteration  # Julia, 38 bytes !x=x*join(x=reverse(x) for _=x[2:end])  Try it online! # 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()}}. 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! 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. Sep 15 '16 at 8:59
• Since no-one said it yet, welcome to PPCG! Sep 15 '16 at 11:39

# 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(""))} 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. 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. 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. 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. Sep 18 '16 at 15:32 • (i%2)*4-1 is the same as i*2%4-1. 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"" 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. 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.

# Keg, 8 bytes

᠀:(⑴;|⑩⑶


Try it online!

I found this to be quite a fun little answer to write.

## Explained

᠀:(⑴;|⑩⑶
᠀:          #Take input as a string (otherwise numbers won't work correctly) and duplicate it, because:
(⑴        #We then push the length of that string onto the stack. The ⑴ op pops the top however, which is why duplication was needed. This will be the loop count of our for loop, started with "("
;       #Decrement that length to avoid off by one error
|      #Branch to the body of the for loop
⑩⑶    #Print the item without popping and then reverse that item
`

Oh unicode... why'd y'all have to be so unevenly widthed for?