Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

Leaderboards

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

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>

share|improve this question
    
In your example, shouldn't that be olleH, not elloH ? – Super Chafouin yesterday
    
@SuperChafouin Haha, you're right. I've fixed that now. – DJMcMayhem yesterday
1  
@Downgoat No, you must take input and output in the same format as the spec describes. – DJMcMayhem yesterday
3  
Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? – Luis Mendo 21 hours ago
2  
@carusocomputing It won't: "You can safely assume that the input string will not be empty, and will only contain printable ASCII." – Martin Ender 16 hours ago

37 Answers 37

Python, 40 bytes

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

A recursive function. Prepends the input string s to the function of the reverse until the counter i exceed the length of s.

share|improve this answer
    
Wow. I was just about to submit a 56 byte python answer, haha – DJMcMayhem yesterday
    
@DJMcMayhem it also beats lambda s:(len(s)*(s+s[::-1]))[:len(s)**2] by one byte. – Jonathan Allan yesterday

Vim, 39, 34 keystrokes

:se ri
Y:s/./<C-r>"/g
<C-o>qqgJC<C-r>"<esc>gJ@qq@q

5 bytes saved thanks to @Lynn!

Here is a gif of it happening live: (Note that this gif is of a previous version since I haven't had time to re-record it yet).

enter image description here

And here is an explanation of how it works:

:se ri                  "Turn 'reverse indent' on.
Y                       "Yank this line
:s/./<C-r>"/g           "Replace every character on this line with the register
                        "We just yanked followed by a newline
<C-o>                   "Jump to our previous location
     qq                 "Start recording in register 'q'
       gJ               "Join these two lines
         C              "Delete this line, and enter insert mode
          <C-r>"<esc>   "Paste the line we just deleted backwards 
gJ                      "Join these two lines
  @q                    "Call macro 'q'. This will run until we hit the bottom of the buffer.
    q                   "Stop recording.
     @q                 "Start our recursive macro

On a side note, Y grabs an extra newline, which is usually an obnoxious feature. This is probably the first ever time that it has actually saved several bytes!

share|improve this answer
1  
Instead of :%s/\n<cr>, you can do v{gJ to save three bytes. – Lynn 21 hours ago
    
A VIM answer?! That's a classy move on your part. – carusocomputing 17 hours ago
    
@Lynn Thanks for the tip! I ended up doing something slightly different and took 5 off instead. – DJMcMayhem 9 hours ago

PHP, 54 52 bytes

(49 bytes, but do not work if string contains '0')

for(;($a=$argv[1])[$i++];)echo$i%2?$a:strrev($a);

(52 bytes)

<?=str_pad('',strlen($a=$argv[1])**2,$a.strrev($a));

(54 bytes)

for(;$i++<strlen($a=$argv[1]);)echo$i%2?$a:strrev($a);
share|improve this answer
    
I completely forgot about str_pad. nice one! – Titus 22 hours ago

Jelly, 4 3 bytes

,Ṛṁ

Try it online! or Verify all test cases.

Saved a byte thanks to @Maltysen.

Explanation

,Ṛṁ  Input: string S
 Ṛ    Reverse S
,     Join S with reverse of S. Makes a list [S, rev(S)]
  ṁ   Mold [S, rev(S)] to len(S) by repeating elements cyclically
      Return and print implicitly as a string
share|improve this answer
1  
mold doesn't need the L – Maltysen yesterday
    
@Maltysen wow thanks, did you know that from the source code or from experience – miles yesterday
    
from experience, I don't know Jelly, but I kinda guessed that's what mold would do on a non-number, since Jelly doesn't really do overloads, also mold kinda reminded me of reshape from J – Maltysen yesterday
    
mold actually takes only iterables, but it casts integers to range first. – Dennis yesterday
1  
Yeah I treated mold as reshape so I just habitually gave it a number. There's so many neat little treats in Jelly, like how an array of strings is just automatically output as a concatenated string – miles yesterday

Brain-Flak, 418 bytes

This is my Brain-Flak masterpiece. It may not be well golfed but the challenge is the most difficult I have ever encountered.

Try it online!

(([])[()]){({}[()]<((({})<{({}[()]<(({}<>))<>>)}{}<>>)<{({}[()]<({}<>)<>([][()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>>)}{}<>([]){{}({}<>)<>([])}{}<>([]){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)>)}{}(({})){(({}[()])<({}<>)<>(({}))({<({}[()])><>({})<>}{})<>{}<>({}<({}<>)<>>)<>({}<>)({}<{(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)>)}{}{}

I am way to tired to explain it now, but I will explain it.

share|improve this answer
    
Amazing. You always blow my mind with what this language can do! :D – DJMcMayhem 23 hours ago

2sable, 3 bytes

Code:

gGÂ

Explanation:

g   # Get the length of the input
 G  # Do the following n - 1 times:
  Â # Bifurcate, which duplicates a and reverses the duplicate

Uses the CP-1252 encoding. Try it online!

share|improve this answer

Perl, 24 bytes

Includes +2 for -lp

Give input on STDIN:

rev.pl <<< Hello!

rev.pl:

#!/usr/bin/perl -lp
s%.%s/.?/chop/eg;$`%eg

Surprisingly this does not use the builtin reverse operator. That name is just soooo long, all solutions I could think of with reverse are at least 1 byte longer.

share|improve this answer

J, 13 8 bytes

Saved 5 bytes thanks to miles!

#;@$];|.

This is a 5-train with the following verbs:

# ;@$ ] ; |.

The inner fork is composed of ] (identity), ; (link), and |. (reverse). Observe:

   (| ; |.) 'Hello!'
+------+------+
|Hello!|!olleH|
+------+------+

The outer two verbs make the rest of the train. # is, in this case, the size of the argument, that is, the length. The verb linking these is ;@$, or ravel over reshape. Observe:

   # 'Hello!'
6
   6 $ (] ; |.) 'Hello!'
+------+------+------+------+------+------+
|Hello!|!olleH|Hello!|!olleH|Hello!|!olleH|
+------+------+------+------+------+------+
   ; 6 $ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   6 ;@$ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ (] ; |.)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ ] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (#;@$];|.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH

Old solution.

[:,|.^:(i.@#)

Simple enough. |. is reverse, and ^: is power conjunction, which repeats it's left verb (right hand) # of times. When the right argument is a verb, that verb is called on the argument. The right verb in this case is range from zero (i.) to the length (#). When raised to an array, the intermediate results are kept. All that needs to be done is to flatten the array with ,.

Intermediate results

   (i.@#) 'Hello!'
0 1 2 3 4 5
   |.^:0 1 2 3 4 5 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   |.^:(i.@#) 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   ([:,|.^:(i.@#)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
share|improve this answer
    
You can save a byte by boxing the length <@# – miles yesterday
    
A neat 8 byte solution is #;@$];|. which boxes the initial and reverse, reshapes the boxed strings and razes them together – miles yesterday
    
@miles whoa, that's pretty neat. – Conor O'Brien 18 hours ago

Minkolang, 17 bytes:

$oId$z$Dz[rz[O]].

Try it here!

Explanation

$o                   Read in whole input as characters
  Id                 Push the length of stack and duplicate
    $z               Pop top of stack and store in register (z)
      $D             Pop top of stack (n) and duplicate whole stack n-1 times
        z[     ]     z times, do the following:
          r          Reverse the stack
           z[O]      z times, pop the top of stack and output as character
                .    Stop.
share|improve this answer

Pip, 11 10 bytes

L#aORVRV:a

Try it online!

Explanation:

            a is first cmdline argument (implicit)
L#a         Loop len(a) times:
      RV:a   Reverse a and assign back to a
   ORV       Output the reverse of a (since it needs to go forward first then backward)
share|improve this answer

Ruby, 39 bytes

->(s){s.reverse!.gsub(/./){s.reverse!}}

I suck at Ruby. Golfing help is appreciated.

Ruby is a really nice language for this because of .reverse!

Explanation

I was hoping it would be someting simple like:

s.gsub(/./){s.reverse!}

but because of boilerplate/challenge restriction it's longer.

What s.reverse! is very useful. s.reverse! is basically s = s.reverse!, meaning it also mutates s.


What each section of the program does is described below:

->(s){             # Lambda with argument s
      s.reverse!   # Reverse `s` see above for details
      .gsub(/./)   # Replace every character with...
      {s.reverse!} # the input reversed!

The thing about s.reverse! that is great is that everytime it is evaluated the string get's flipped. So as it replaces the string. s is modified!

share|improve this answer
    
With the -p flag you can save 4 bytes: $_.reverse!;gsub(/./){$_.reverse!} – Jordan yesterday
    
@Jordan would't I need a .chomp though on the $_? it seems to include the newline at the moment – Downgoat yesterday
    
Not if you do something like ruby -pe '$_.reverse!;gsub(/./){$_.reverse!}' < file.txt where file.txt is a line without the trailing newline :V Anyways, if you decide not to do that, you don't need parens on the lambda so ->s works – Value Ink yesterday
    
@ValueInk, you can provide newlineless input without file if you pipe it. Or you can even type it manually, just not press Enter: i.stack.imgur.com/6luxM.png – manatwork 20 hours ago
    
@Downgoat, as shorter alternative for .chomp there is the -l command-line switch, just like in Perl. – manatwork 20 hours ago

JavaScript (ES 6), 59 50 bytes

9 Bytes thanks to Hedi and Huntro.

f=(s,n=1)=>s[n]?s+f([...s].reverse().join``,n+1):s

recursive function.

Reversing the string takes almost half of the size (25 22 bytes!) ...
Why isn´t there a native way for that?

share|improve this answer
1  
You could use s[n]?... intead of n<s.length?... – Hedi 23 hours ago
1  
You can also save 3 bytes by using [...s] instead of s.split`` – Huntro 23 hours ago
    
yea 36 bytes ideally f=(s,n=1)=>n==1?s:s+s.reverse(),n-1) – caub 16 hours ago
    
non recursive one f=(s,n=1)=>Array.from({length:n},(_,i)=>i%2?s.reverse():s).j‌​oin``) that would too be better with some better function for range – caub 16 hours ago
    
@caub: SyntaxError: Unexpected token ) JS has no native string reversion. SyntaxError: Invalid or unexpected token for your second suggestion. What browser does that work in? – Titus 13 hours ago

Java, 127 111 88 bytes

(s,r)->{for(int i=0;i++<s.length();)r+=i%2<1?new StringBuffer(s).reverse():s;return r;};

Ungolfed test program

    public static void main(String[] args) {
    BiFunction<String, String, String> func = (s, r) -> {
        for (int i = 0; i++ < s.length();) {
            r += i % 2 < 1 ? new StringBuffer(s).reverse() : s;
        }
        return r;
    };
    System.out.println(func.apply("Hello!", ""));
}
share|improve this answer
    
This can be golfed some more: (s,r)->{for(int i=0;i++<s.length();)r+=i%2<1?s:new StringBuffer(s).reverse();return r;}; (88 bytes). Also, I would specify that this is Java 8. – Kevin Cruijssen 21 hours ago
    
Na, it's fine to assume that his is using the latest version of Java. – Basically Alan Turing 20 hours ago
    
@KevinCruijssen Java 7 is not supported anymore (except with big $$$). We shouldn't have to specify the version of Java. Also, if you write as Java 7, most of the answers can be written in Java 1.1 or 1.2. So shouldn't you write the lowest version with which it works? If the code in this answer was Java 7 compliant, it'd be Java 1.2 compliant, and... would still work in Java 8. – Olivier Grégoire 17 hours ago

Haskell, 40 36 32 Bytes

m s=take(length s^2)$cycle$s++reverse s

Example:

*Main> m "Hello!"
"Hello!!olleHHello!!olleHHello!!olleH"

Even shorter (credit to Damien):

q s=zip(s>>[s,reverse s])s>>=fst

s>>[s,reverse s] cycles ["abc","cba",...] which is zipped to correct size and concatMap'ped with fst

share|improve this answer
1  
q s=zip(s>>[s,reverse s])s>>=fst – Damien 18 hours ago
1  
Or Pointfree one with same size: (>>=fst).(iterate reverse>>=zip) – Damien 18 hours ago

PHP, 54 bytes

while($i++<strlen($s=$argv[1])){echo$s;$s=strrev($s);}

There are a lot of ways to do that, in almost every language I guess.


These two are my favourites:

an evil eval (62 bytes)

eval(str_repeat('echo$s;$s=strrev($s);',strlen($s=$argv[1])));

and a substr solution (69 bytes)

<?=substr(str_repeat(($s=$argv[1]).strrev($s),$n=strlen($s)),-$n*$n);

and while we´re at unsensible coding, take these 61:

$s=$argv[1];L:echo$s;$s=strrev($s);if(++$i<strlen($s))goto L;
share|improve this answer

Brachylog, 16 bytes

l-I,?r:?r:Ij@2hc

Try it online!

Explanation

l-I,                I = length(Input) - 1
    ?r              Reverse the Input
      :?r           The list [Input, Reverse of the Input]
         :Ij        Append I times that list to itself
            @2h     Split in half and take the first part
               c    Concatenate into a string
share|improve this answer

Retina, 27 bytes

Byte count assumes ISO 8859-1 encoding.

.
±$_
O$^`(?(\G)[^±]|±)

±

Try it online!

Explanation

.
±$_

Replace each character with the entire input, preceded by ± to separate copies.

O$^`(?(\G)[^±]|±)

The regex matches the characters in every other copy, by either matching a ± that is not adjacent to the previous match, or a non-± that is. These characters are reversed. Since each copy is the same width that is identical to reversing each copy individually.

±

Remove the separators.

share|improve this answer

CJam, 10 bytes

l_,({_W%}*

Try it online!

share|improve this answer

Straw, 10 bytes

<:(:>"),*&

Try it online!

<:(:>"),*&
<          Take the input       (Stack: ["", input])
 :         Duplicate            (Stack: ["", input, input])
  (        Start a string
   :       Duplicate
    >      Output
     "     Reverse
      )    End the string       (Stack: ["", input, input, ':>"'])
       ,   Swap                 (Stack: ["", input, ':>"', input])
        *  Unary multiplication (Stack: ["", input, ':>"'*length of input])
         & Evaluate             (Stack: ["", input])
share|improve this answer

PowerShell v2+, 57 bytes

param($a)-join(1..($x=$a.length)|%{($a[$x..0],$a)[$_%2]})

No real clean way to get string lengths or reverse 'em, so this is pretty lengthy.

Takes input $a, loops from 1 to $a.length (stored in $x for use later). Each iteration we use a pseudo-ternary to index into an array of either $a or $a[$x..0] (i.e., reversed), based on whether our input number is odd/even [$_%2]. These are all encapsulated in parens and -joined together to form a single string. That's left on the pipeline, and output is implicit.

PS C:\Tools\Scripts\golfing> .\stringgnirts.ps1 'TimmyD'
TimmyDDymmiTTimmyDDymmiTTimmyDDymmiT
share|improve this answer

Dyalog APL, 8 bytes

∊≢⍴⊂,⊂∘⌽

flatten

the tally

cyclically reshaping

the enclosed argument

, followed by

⊂∘⌽ the enclosed reversed argument

TryAPL online!

-1 byte thanks to jimmy23013.

share|improve this answer
    
∊≢⍴⊂,⊂∘⌽. And you counted 1 byte less. – jimmy23013 16 hours ago
    
@jimmy23013 I wrote the final score. ;-) – Adám 14 hours ago

Java, 151 bytes

public static void r(String s){String t = new StringBuffer(s).reverse().toString();for(int i=0;i<s.length();i++){System.out.print(((i%2==1)?t:s));}}

}

Ungolfed:

public static void r(String s) {
    String t = new StringBuffer(s).reverse().toString();
    for(int i = 0; i < s.length();i++) {
        System.out.print(((i % 2 == 1) ? t : s));
    }
}

share|improve this answer
    
Hi, welcome to PPCG! First of all I'd like to recommend to read through Tips for golfing in Java. As for your code, there are a few things that can still be golfed: You can remove the public static before your method. You can remove the spaces between t=new StringBuffer. You can remove the unnecessary parenthesis and brackets. And you can swap the module check from ==1 to <1 (which is equivalent to ==0 for non-negative numbers). Also, you can move the i++ to the last usage inside the for-loop. – Kevin Cruijssen 23 hours ago
3  
So in total it becomes: void r(String s){for(int i=0;i<s.length();)System.out.print(i++%2<1?s:new StringBuffer(s).reverse()+"");} (105 bytes) – Kevin Cruijssen 23 hours ago

C#, 94 bytes

using System.Linq;string R(string n)=>string.Concat(n.SelectMany((c,i)=>1>i%2?n:n.Reverse()));

76 bytes for the method + 18 bytes for LINQ import.

How it works:

using System.Linq; // Required for LINQ extension methods.

string R(string n) => 
    string.Concat( // Concatenate the following chars into a single string
        n.SelectMany( // Enumerate each char in n, flattening the returned IEnumerable<char>'s into a single IEnumerable<char>
            /*IEnumerable<char> Lambda*/(/*char*/ c, /*int*/ i) => // i = index in n
                1 > i % 2 // Check if i is even or odd
                    ? n // if i is even, add n to the concat
                    : n.Reverse() // else reverse n and concat that
        )
    )
;
share|improve this answer

Vim + coreutils, 32 keystrokes

You can never have too many Vim answers.

qqYv:!rev
Pjq@=len(@")
@q2dkv{gJ

Explanation

qq               " Start recording macro
Y                " Yank (copy) line
v:!rev<CR>       " Reverse line with coreutils rev command
Pj               " Paste yanked line above this line
q                " Stop recording
@=len(@")<CR>@q  " Playback macro once for each character
2dk              " Delete last 3 lines
v{gJ             " Join lines
share|improve this answer

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

share|improve this answer

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
share|improve this answer

Groovy, 51 bytes

def d(s){s.size().times{print(it%2?s.reverse():s)}}
share|improve this answer
    
Anonymous function/proc/lambda/closure/whatever each language may call them, are also acceptable: {s->s.each{print(s);s=s.reverse()}}. – manatwork 21 hours ago
    
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 21 hours ago

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()));
}
share|improve this answer
    
All the usings are missing in this answer: those would add another 31 bytes. – Scepheo 21 hours ago
    
Since no-one said it yet, welcome to PPCG! – Erik the Golfer 18 hours ago

R, 53 bytes

Assumes that the input is space- or newline-separated for each character.

cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")

Some test cases:

> cat(rep(c(i<-scan(,""),rev(i)),len=length(i)^2),sep="")
1: h e l l o !
7: 
Read 6 items
hello!!ollehhello!!ollehhello!!olleh

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a
2: 
Read 1 item
a

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a b c d
5: 
Read 4 items
abcddcbaabcddcba

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: O K !
4: 
Read 3 items
OK!!KOOK!

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 8 1 5 1 6 2 3 4 2
11: 
Read 10 items
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: P P C G
5:    
Read 4 items
PPCGGCPPPPCGGCPP

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 2
3: 
Read 2 items
4224
share|improve this answer

Octave, 39 bytes

@(x)[x'+0*x;flipud(x'+0*x),''](1:end/2)

f('Hello!')
ans = Hello!!olleHHello!!olleHHello!!olleH

Explanation:

@(x)            % Take x as input, inside apostrophes 'Hello!'
x'+0*x          % Create a mesh of the ASCII-code of the input letters
                % For input `bcd` this will be:
                %    98    98    98
                %    99    99    99
                %   100   100   100
;flipud(x'+0*x) % Concatenate vertically to create:
                %    98    98    98
                %    99    99    99
                %   100   100   100
                %   100   100   100
                %    99    99    99
                %    98    98    98
___,'']         % Short cut to convert ASCII-code to characters
(1:end/2)       % Display the first half of this array of letters, as a
                % horizontal string
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.