55
\$\begingroup\$

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>

\$\endgroup\$
9
  • \$\begingroup\$ In your example, shouldn't that be olleH, not elloH ? \$\endgroup\$
    – Arnaud
    Commented Sep 15, 2016 at 3:27
  • 2
    \$\begingroup\$ @Downgoat No, you must take input and output in the same format as the spec describes. \$\endgroup\$
    – DJMcMayhem
    Commented Sep 15, 2016 at 4:15
  • 4
    \$\begingroup\$ Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? \$\endgroup\$
    – Luis Mendo
    Commented Sep 15, 2016 at 8:39
  • 2
    \$\begingroup\$ @carusocomputing It won't: "You can safely assume that the input string will not be empty, and will only contain printable ASCII." \$\endgroup\$ Commented Sep 15, 2016 at 13:50
  • 1
    \$\begingroup\$ 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... \$\endgroup\$ Commented Sep 15, 2016 at 14:59

106 Answers 106

1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 107 91 bytes

	O =N =INPUT
I	X =LT(X,SIZE(N) - 1) X + 1	:F(O)
	N =REVERSE(N)
	O =O N	:(I)
O	OUTPUT =O
END

Try it online!

This should now be fairly close to Suever's MATL solution.

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 25 bytes

{S:g{.}=$++%2??.flip!!$_}

Try it online!

-4 bytes thanks to Jo (the) King!


Perl 6, 29 bytes

{S:g/./{$/.to%2??$_!!.flip}/}

Wanted to avoid a concatenation, so this just substitutes every character S:g/./ ... / with either the input $_ or its reverse .flip depending on whether the match position $/.to is odd or even %2.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ can't use $++ here? \$\endgroup\$
    – Ven
    Commented Mar 21, 2019 at 21:18
  • \$\begingroup\$ @Ven I think because its state gets reset every time the {} interpolation happens. However, if the code isn't being interpolated, this can be 25 bytes \$\endgroup\$
    – Jo King
    Commented Mar 22, 2019 at 2:26
1
\$\begingroup\$

C# (Visual C# Interactive Compiler), 43 bytes

s=>s.SelectMany((_,i)=>i%2<1?s:s.Reverse())

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pip, 20 17 bytes

Fi,#a{i%2?ORVaOa}

Try it online!

(RV reverses iterable). The program outputs the string on even steps and the reverse on odd steps

\$\endgroup\$
1
\$\begingroup\$

Python2, 109 99 89 bytes

def f(s,o=''):
 r=s[::-1]
 for i in range(len(s)):
  if i%2==0:o+=s
  else:o+=r
 return o

Try it online!

or

Python2, 53 bytes

Saved 36 bytes, thanks to Jonathan French's solution:

lambda s:''.join(s[::~i%2*2-1]for i in range(len(s)))

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 53 bytes. \$\endgroup\$ Commented Aug 12, 2019 at 3:30
  • \$\begingroup\$ As general golfing tips: You can negate i%2==0 to i%2!=0 and swap your two branches. Then the condition reduces to i%2. Furthermore, r is only referenced once and thus can be substituted with its value. You can shrink the iterative for loop into a generator and concatenate the result, yielding a one-line lambda expression. I also recommend reading the Python tips page. \$\endgroup\$ Commented Aug 12, 2019 at 3:33
  • \$\begingroup\$ Thanks, these are all terrific tips and great link! If a comment presents an improvement that follows the basic idea of the original, should I either replace the original or add an update section to it? \$\endgroup\$ Commented Aug 12, 2019 at 3:37
  • \$\begingroup\$ It is up to you. Most of the time, a golfing suggestion is incorporated into the answer, improving its byte count and crediting the source. Sometimes the changes are too drastic and one wants to retain multiple solutions, albeit of differing byte count. \$\endgroup\$ Commented Aug 12, 2019 at 3:43
1
\$\begingroup\$

PowerShell, 44 bytes

-join(($a=$args)|%{$a;$a=$a[-1..-$a.Count]})

Try it online!

Takes input via splatting, essentially making it an array of chars.

\$\endgroup\$
1
\$\begingroup\$

K (oK), 18 bytes

Solution:

,//(#x)#(,;|)@\:x:

Try it online!

Explanation:

Apply enlist , and reverse | to the input and take length-of-input from this

,//(#x)#(,;|)@\:x: / the solution
                x: / store input as x
             @\:   / apply (@) each-left (\:)
        ( ; )      / two-item list
           |       / reverse
         ,         / enlist
       #           / take
   (  )            / do this together
    #x             / count x
,//                / flatten (,/) until converges
\$\endgroup\$
1
\$\begingroup\$

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.
```
\$\endgroup\$
1
\$\begingroup\$

Ruby, 34 bytes

->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 ($>).

\$\endgroup\$
1
  • \$\begingroup\$ You can use the chars function instead of each_char \$\endgroup\$
    – Jo King
    Commented Jun 17, 2021 at 6:38
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Julia, 38 bytes

!x=x*join(x=reverse(x) for _=x[2:end])

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Lua, 59 51 bytes

Thanks @Steffan!

for x=0,arg[1]do a=arg[2]io.write(a,a:reverse())end

Attempt This Online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 51 \$\endgroup\$
    – naffetS
    Commented Jan 31, 2023 at 15:46
  • \$\begingroup\$ This doesn't work for odd-length strings, and I don't think you can take N/2 as input. \$\endgroup\$
    – naffetS
    Commented Apr 27, 2023 at 1:21
1
\$\begingroup\$

Java 8, 108 bytes

Even if there already is a better Java solution posted, here is a different approach using a single inline stream :

s->s.chars().mapToObj(e->"").reduce("",(a,b)->a.length()/s.length()%2<1?a+s:a+new StringBuffer(s).reverse())

Try it online!


And here is a janky stream solution avoiding the use of StringBuffer(s).reverse() (and exploiting the fact that the input and output can't contain \n), but requiring an additional substring because the result was containing two times the answer, sadly :( 149 bytes :

s->s.chars().mapToObj(e->""+(char)e).reduce(s.replaceAll(".","\n"),(a,b)->a.replace("\n",b+"\n"+b)).replace("\n","").substring(s.length()*s.length())
\$\endgroup\$
1
\$\begingroup\$

Python 3, 61 bytes

def b(x):
 f,q=len(x),''.join([x,x[::-1]]*f)
 return q[:f**2]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Arturo, 39 bytes

$->s[s loop size s=>[reverse prints<=]]

Try it

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Groovy, 51 bytes

def d(s){s.size().times{print(it%2?s.reverse():s)}}
\$\endgroup\$
2
  • \$\begingroup\$ Anonymous function/proc/lambda/closure/whatever each language may call them, are also acceptable: {s->s.each{print(s);s=s.reverse()}}. \$\endgroup\$
    – manatwork
    Commented Sep 15, 2016 at 8:19
  • \$\begingroup\$ 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! \$\endgroup\$
    – norganos
    Commented Sep 15, 2016 at 8:36
0
\$\begingroup\$

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()));
}
\$\endgroup\$
2
  • \$\begingroup\$ All the usings are missing in this answer: those would add another 31 bytes. \$\endgroup\$
    – Scepheo
    Commented Sep 15, 2016 at 8:59
  • \$\begingroup\$ Since no-one said it yet, welcome to PPCG! \$\endgroup\$ Commented Sep 15, 2016 at 11:39
0
\$\begingroup\$

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);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ {s in print((0..<s.characters.count).map{$0%2==0 ?s:String(s.characters.reverse())}.joinWithSeparator(""))} \$\endgroup\$ Commented Sep 17, 2016 at 11:15
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – Scepheo
    Commented Sep 15, 2016 at 12:32
  • \$\begingroup\$ 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. \$\endgroup\$
    – manatwork
    Commented Sep 15, 2016 at 12:35
  • \$\begingroup\$ 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. \$\endgroup\$
    – ATaco
    Commented Sep 16, 2016 at 0:55
0
\$\begingroup\$

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!
\$\endgroup\$
0
\$\begingroup\$

Python 3, 84 70 67 characters

def s(d,i=1):
 t=d[::(i%2)*2-1]
 if i<len(d):t+=s(d,i+1)
 return t
\$\endgroup\$
4
  • \$\begingroup\$ You can insert r+=... to the same line as the for loop. \$\endgroup\$
    – Yytsi
    Commented Sep 18, 2016 at 15:32
  • \$\begingroup\$ (i%2)*4-1 is the same as i*2%4-1. \$\endgroup\$
    – Wheat Wizard
    Commented Sep 19, 2016 at 1:40
  • \$\begingroup\$ Try s=lambda d,i=0:d[::1-i*2%4]+s(d,i+1)if d[i:]else"" \$\endgroup\$
    – Wheat Wizard
    Commented Sep 19, 2016 at 2:42
  • \$\begingroup\$ 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. \$\endgroup\$
    – Wheat Wizard
    Commented Sep 19, 2016 at 2:52
0
\$\begingroup\$

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 )&  »;
\$\endgroup\$
0
\$\begingroup\$

ES7, 60 bytes

b=>{for(c=b,d=0;d++<b.length;)c+=d%2?b:b.reverse();return c}
\$\endgroup\$
0
\$\begingroup\$

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!
\$\endgroup\$
0
\$\begingroup\$

Red, 43 bytes

func[s][foreach c s[prin copy s reverse s]]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Factor, 62 bytes

: f ( x -- x ) [ length ] keep [ dup write reverse ] repeat ; 

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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