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
    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
    Sep 15, 2016 at 4:15
  • 4
    \$\begingroup\$ Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? \$\endgroup\$
    – Luis Mendo
    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\$ 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\$ Sep 15, 2016 at 14:59

105 Answers 105

2
\$\begingroup\$

bash + util-linux, 68 58 53 bytes

y=$1;for((i;i<${#1};i++)){ echo -n $y;y=`rev<<<$y`;}

Explanation

Two things with the for loop:

  • There is an apparently undocumented way of writing for loops where one replaces the do and done keywords with curly braces { and }. The space after the first bracket is necessary, and the semicolon at the end is also necessary.
  • It turns out that in the "C-style" for loops, you can just initialize with i; instead of using i=0;.
  • The ${#1} part of the condition i < ${#1} refers to the length of our input (the first parameter $1). In general, you can use ${#foo} to retrieve the size of the string $foo.

Additionally:

  • rev is the tool in util-linux that reverses a string.
  • We need to pass the -n flag to echo to get rid of newlines.
  • The expression rev<<<$y is called a here-string (see this relevant tldp.org page), which passes the variable $y to the standard input of rev.
\$\endgroup\$
4
  • \$\begingroup\$ Please explain some of your knowledge. Also perhaps the space before the echo may be removable, I am not knowledgable on bash though \$\endgroup\$ Sep 18, 2016 at 1:47
  • \$\begingroup\$ @RohanJhunjhunwala Added a little explanation to the answer to maybe help clarify some things. Also: when omitting the do and done keywords in a for loop, you actually do need that space! \$\endgroup\$
    – frame
    Sep 19, 2016 at 23:37
  • \$\begingroup\$ +1 looks good now. I onlly commented because your code drew an automatic low quality flag. Code-only answers get auto flagged \$\endgroup\$ Sep 20, 2016 at 0:39
  • \$\begingroup\$ y=$1;for((;i<${#1};i++)){ printf $y;y=`rev<<<$y`;} ... saved a couple of bytes \$\endgroup\$
    – roblogic
    Mar 23, 2019 at 20:03
2
\$\begingroup\$

Japt, 11 bytes

ê1 pUÊ ¯Uʲ
ê1          // Append the reverse of the input to the input,
   pUÊ      // then repeat it input length times
       ¯Uʲ // and finally trim to length input length squared.

Try it online!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ You're forgetting about î again, aren't you?! \$\endgroup\$
    – Shaggy
    Apr 13, 2018 at 16:15
  • \$\begingroup\$ @Shaggy I tried using it, but for the life of me, I can't get the hang of it. :P Thanks a lot for the example, though! \$\endgroup\$
    – Etheryte
    Apr 13, 2018 at 16:16
  • \$\begingroup\$ Sorry, posted the wrong link, it's actually 6 bytes. \$\endgroup\$
    – Shaggy
    Apr 13, 2018 at 16:17
  • \$\begingroup\$ Here's a 6 byte solution \$\endgroup\$
    – Oliver
    Apr 13, 2018 at 23:25
  • 1
    \$\begingroup\$ @Shaggy I wouldn't mind, and it's different enough than Nit's answer. Go for it man. \$\endgroup\$
    – Oliver
    Apr 14, 2018 at 0:34
2
\$\begingroup\$

05AB1E, 7 bytes

vDR}v}J

Try it online!

Will continue to work on it. I don't really like the "v}" part of it, can probably save a byte there.

Explanation

vDR}v}J

v         ; Iterates through each character
 D        ; Duplicate top of stack
  R       ; Push top of stack reversed
   }      ; end for loop
   v}     ; same as other v, effectively pops top of stack off
     J    ; Join everything together
\$\endgroup\$
2
  • 2
    \$\begingroup\$ vÂ}\J 5 bytes is the same as your code, but with the builtins you were looking for. :) Â is Bifurcate (short for Duplicate & Reverse, which is exactly what you're doing). \ deletes the top item on the stack. \$\endgroup\$ Oct 24, 2018 at 14:01
  • \$\begingroup\$ Also 5 bytes: R‚I∍J. \$\endgroup\$
    – Grimmy
    Jan 22, 2020 at 16:56
2
\$\begingroup\$

Keg, 6 bytes

(^(:,"

How it works

    Implicit Reversed Input
(   Runs X times, where X is the length of the stack
^   Reverse the stack
(   Runs X times, where X is the length of the stack
:,  Prints the top item of the stack as a character
"   Rolls the stack to the right (puts the top of the stack to the bottom)
    Ending brackets get auto-completed

Try it Online!

\$\endgroup\$
3
  • \$\begingroup\$ The TIO does not work anymore... \$\endgroup\$
    – user85052
    Aug 12, 2019 at 2:48
  • \$\begingroup\$ Oh, did the latest pull request change anything I used here, because it was working before that? \$\endgroup\$
    – EdgyNerd
    Aug 12, 2019 at 6:46
  • \$\begingroup\$ Use the -lp and -ir flags instead \$\endgroup\$
    – lyxal
    Feb 4, 2020 at 7:34
2
\$\begingroup\$

Zsh, 46 41 bytes

repeat $#1 s+=$1${(j::)${(Oas::)1}}
<<<$s

Try it online! Try it online!

       ${(Oas::)1}
       ${       1}    # take first parameter
         (  s::)      # split into characters
         (Oa   )      # reverse order
${(j::)           }   # join
\$\endgroup\$
2
\$\begingroup\$

Java (JDK), 68 bytes

s->{var r=""+s;for(int i=s.length();i-->1;)r+=s.reverse();return r;}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

K (ngn/k), 14 bytes

{,/(#1_x)|:\x}

Try it online!

  • (#1_x)|:\x set up a n-dos scan, running |: (i.e., reverse) on the original input x a number of times equal to the length of the input minus 1
  • ,/ flatten (and implicitly return) the above
\$\endgroup\$
2
\$\begingroup\$

Thunno J, \$ 7 \log_{256}(96) \approx \$ 6 bytes

(actually 5.76 bytes but that doesn't show up on the leaderboard)

rDeKDrD

Attempt This Online!

Explanation

rDeKDrD  # Implicit input
r        # Reverse the input
 D       # Duplicate and get the length
  eK     # Loop through, popping the loop variable:
    Dr   #  Duplicate and reverse
      D  #  And duplicate (since this will get popped)
         # The J flag joins this list of strings
         # Implicit output

Thunno J, \$ 10 \log_{256}(96) \approx \$ 8.23 bytes

DLsDrZPsZG

Attempt This Online!

Explanation

DLsDrZPsZG  # Implicit input
DL          # Duplicate and get the length
  sDr       # Swap, duplicate, and reverse
     ZP     # Pair with the reversed copy
       sZG  # Extend this list to the length of the input
            # The J flag joins this list of strings
            # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Lua, 49 bytes

s=...print((s..s:reverse()):rep(#s):sub(1,#s*#s))

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ s=...for i=1,#s do io.write(s)s=s:reverse()end \$\endgroup\$
    – naffetS
    Apr 27 at 1:19
2
\$\begingroup\$

Thunno 2, 5 bytes

l{D¢r

Attempt This Online!

Explanation

l{D¢r  # Implicit input
l{     # Repeat length of input times:
  D¢   #  Print TOS without a newline, without popping
    r  #  Reverse for next iteration
\$\endgroup\$
2
\$\begingroup\$

Nekomata, 5 bytes

xᵐᵑ↔j

Attempt This Online!

xᵐᵑ↔j
x       Range from 0 to length of input - 1
 ᵐ      Map
  ᵑ       Apply the next function n times
   ↔        Reverse
    j   Concatenate
\$\endgroup\$
1
\$\begingroup\$

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

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

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.

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

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

Pyth, 6 bytes

Vzp~_z

Try it online!

Explanation

Vzp~_z
Vz      For every character in z (the input)
  p  z  Print z
   ~_z  Reverse z
\$\endgroup\$
1
\$\begingroup\$

Pyke, 8 7 bytes

VoI_Q(s

Try it here!

\$\endgroup\$
2
  • \$\begingroup\$ Works, but also gives an error "RUNNING: 'VoI_Q(s' Missing arg to Repeat, evaling input.BAD EVAL STACK" \$\endgroup\$
    – GolezTrol
    Sep 16, 2016 at 21:32
  • \$\begingroup\$ @GolezTrol If you run it without warnings it doesn't do that. Also by default stderr can be ignored \$\endgroup\$
    – Blue
    Sep 16, 2016 at 21:35
1
\$\begingroup\$

Lua, 66 bytes

function f(s,i)j=i or 0return#s>j and s..f(s:reverse(),j+1)or''end

Try it on ideone!

\$\endgroup\$
1
  • \$\begingroup\$ While my Lua solution is shorter (62 bytes) and is full program, your is far more creative. Good job! \$\endgroup\$ Aug 1, 2019 at 11:54
1
\$\begingroup\$

Vitsy, 10 bytes

Wl\[::ZYr]

W          Grab a line from STDIN.
 l\[     ] Store the length of the stack as x, do the stuff in brackets x times.
    ::     Clone the current stack twice.
      Z    Output the current stack.
       Y   Pop and dump this stack, returning back to previous.
        r  Reverse the current stack.

Try it online!

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

Haxe, 121 118 117 bytes

function R(s:String){var r="",o="",l=s.length;for(i in-l+1...1)r+=s.charAt(-i);for(i in 0...l)o+=i%2<1?s:r;trace(o);}

Reverting the string took a lot of bytes :(

Testcases

R("a")
a

R("Hello!")
Hello!!olleHHello!!olleHHello!!olleH

R("4815162342")
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184
\$\endgroup\$
5
  • \$\begingroup\$ Could you link to a online test suite or some other resource to test this code? I am having a spot of trouble compiling your code on my machine. \$\endgroup\$
    – Wheat Wizard
    Sep 18, 2016 at 15:39
  • \$\begingroup\$ @WheatWizard Try this: try.haxe.org/#eE97b \$\endgroup\$
    – Yytsi
    Sep 18, 2016 at 15:44
  • \$\begingroup\$ Couldn't you split the string to an array of char and reverse that array? (if it's shorter...) \$\endgroup\$
    – Sake
    Sep 18, 2016 at 16:53
  • \$\begingroup\$ @PaulPicard Tried that already, but it was longer :( \$\endgroup\$
    – Yytsi
    Sep 18, 2016 at 16:58
  • \$\begingroup\$ @PaulPicard FWIW: it's actually longer to reverse the string inside an array comprehension, and join back together, than the method I use here :D \$\endgroup\$
    – Yytsi
    Sep 19, 2016 at 3:52
1
\$\begingroup\$

><>, 40 bytes

<v?(0:i
l\~l&r
$<v!?:-1}o:
;^>~rl&1-:&?!

Try it online!

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

Vimscript - 109 bytes

@DJMcMayhem already beat me to it, but because I did it anyway, here's my losing answer. I thought reversing a string would be easier though!

fu A(s)
let i=0
wh(i<len(a:s))
exe "norm A". [a:s,join(reverse(split(a:s,'\zs')),'')][i%2]
let i+=1
endw
endf

Ungolfed

function! A(s)
  let reversed=join(reverse(split(a:s,'\zs    ')),'')
  let both=[a:s,reversed]
  let i=0
  while(i<len(a:s))
    exe "norm a".both[i%2]
    let i+=1
  endwhile
endfunction
\$\endgroup\$
1
\$\begingroup\$

Excel VBA, 59 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window

a=[A1]:For i=1To Len(a):?IIf(i mod 2,a,StrReverse(a));:Next
\$\endgroup\$
1
\$\begingroup\$

Pushy, 5 bytes

NL:"@

Try it online!

Explanation

N          \ Suppress newlines in printing
 L:        \ Len(String) times do:
   "       \    Print
    @      \    Reverse
\$\endgroup\$
1
\$\begingroup\$

CJam, 15 10 bytes

q_,{_W%}*;

Explanation:

e.g input: "hello"
q //reads input, pushes to the stack. Stack: hello
  _ //duplicates it. Stack: hello, hello
   , //finds the length.  Stack: hello, 5
    { //starts a block.
     _ //duplicates the input. WouldBeStack: hello hello
      W // -1. WouldBeStack: hello -1
       % // Reverse (-1 = reverse, % = select every nth item). WouldBeStack: hello olleh
         } //end the block. Stack: hello, 5, {_W%}
           * //repeat the block for length times. Stack: hello, olleh, hello, olleh, hello, olleh
              ; //discard the last element

Try it online!

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

Add++, 23 bytes

L,dbRB]AbLdVß*GB VcGbUJ

Try it online!

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

Gol><>, 16 bytes

iEv
|;>lFrllKRo~

Try it online!

How it works

iEv

i    Take input as a char
 E   If the last input was EOF, pop; otherwise skip once
iEv  Take all input until EOF, then move to the next line

|;>lFrllKRo~

  >           Move right
   l          Push stack length (== string length)
    F         Pop x and repeat up to matching `|` x times

              [...string]
     r        Reverse stack
              [...rstring]
      ll      Push n, n+1
              [...rstring n n+1]
        K     Pop x and push copy of top x elements
              [...rstring n ...rstring n]
         R    Pop x and repeat the next instruction x times
          o   Pop and print as char
         Ro   Pop n and print n chars in reverse order
              [...rstring n]
           ~  Pop and discard
              [...rstring]

|             End `F` loop
 ;            Halt

Alternative solution, 16 bytes

iEv
|;>lFrlFLko|

Try it online!

How it works

iEv           Same as above

|;>lFrlFLko|

   l          Push n
    F         Pop n, repeat outer loop n times
     r        Reverse stack
      l       Push n
       F      Pop n, repeat inner loop n times
        L     Push loop counter (refers to the inner loop)
         k    Pop x and copy the x-th element to the top
          o   Pop and print as char
           |  Close inner loop
|             Close outer loop
 ;            Halt
\$\endgroup\$
1
\$\begingroup\$

><>, 34 bytes

l::f1.>1!<-{:o$61.
:?!;1-$:?^~r:@@

Input for using the -v flag.

Explanation

l::f1.Captures the length of the input, and creates two copies of it. One of the copies is used to keep track of the number of loops, the other one is used in the loop that prints the string. After that, the program teleports to the end of the second line, wraps around, and enters the main loop.

:?!;1-$ Checks if the program has printed the string n times, and if so, it terminates. Otherwise, it decrements the number of strings remaining.

:?^~r:@@ Checks if the program is done printing one iteration of the loop. If so, it reverses the string.

>1!<-{:o$61. Prints the next character in the string, and decrements the index. Teleports back to previous conditional.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ The flag for strings is the -s flag, whereas -v is used for numbers. The other flags (-t and -a) are rarely used. 23 bytes. \$\endgroup\$
    – Jo King
    Apr 13, 2018 at 11:00
1
\$\begingroup\$

Tcl, 77 bytes

proc S {s i\ 0} {if $i<[string le $s] {set s $s[S [string rev $s] [incr i]]}}

Try it online!


Tcl, 88 bytes

proc S s {time {append r [expr [incr i]%2?"$s":"[string rev $s]"]} [string le $s]
set r}

Try it online!


Tcl, 91 bytes

proc S s {append r $s
time {set r $r[set s [string rev $s]]} [expr [string le $s]-1]
set r}

Try it online!

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

Cubix, 24 bytes

..@wA#s?sBp\).W\oq>(?v()

Try it online!

Unwraps onto the following cube

    . .
    @ w
A # s ? s B p \
) . W \ o q > (
    ? v
    ( )

Watch it run

  • A# Take all from input and push the number of items on the stack. This includes the -1 for the end of input.
  • s? Swap the TOS and test value
    • wsBp\((? If negative (end of word), change lane to the right, swap TOS, reverse stack, bring botton of stack to the top, decrement twice and test
      • W#@ If 0 (repetitions finished) change lane to the left, redundant count of stack and halt
      • v)>()W If still positive, redirect down, increment, redirect right, decrement, increment and shift lane right back into the print loop
    • \oq>()W If positive, reflect left, output character, push TOS to bottom, redirect right, increment, decrement and shift lane left into the print loop
\$\endgroup\$

Your Answer

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

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