44
\$\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\$
  • \$\begingroup\$ In your example, shouldn't that be olleH, not elloH ? \$\endgroup\$ – Arnaud Sep 15 '16 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 '16 at 4:15
  • 4
    \$\begingroup\$ Shouldn't the title be StringgnirtSStringgnirtSStringgnirtS? \$\endgroup\$ – Luis Mendo Sep 15 '16 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\$ – Martin Ender Sep 15 '16 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\$ – Magic Octopus Urn Sep 15 '16 at 14:59

88 Answers 88

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\$
  • 1
    \$\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\$ – Kevin Cruijssen Oct 24 '18 at 14:01
2
\$\begingroup\$

brainfuck, 71 49 43 bytes

,[>+[>+<-],]>[<<[<]>[.>]>-[<<[.<]>[>]>-<]>]

Try it online!

Thanks to Jo King for saving 6 bytes.

[Tape: [Letters], 0, counter]
,[          while input
  >+        increment old counter
  [>+<-]    move counter to next position
  ,         input next
]
>[          while counter
  <<[<]>    go to first letter
  [.>]      print word forwards
  >-        decrement counter
  [         if counter
    <<      go to last letter
    [.<]    print word backwards
    >[>]>-  decrement counter
    <       exit if
  ]
  >         go to counter
]
\$\endgroup\$
  • \$\begingroup\$ Thank you, Jo King. I didn't think it would be shorter that way. \$\endgroup\$ – Dorian Aug 1 '19 at 7:53
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\$
  • \$\begingroup\$ The TIO does not work anymore... \$\endgroup\$ – a'_' Aug 12 '19 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 '19 at 6:46
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\$
  • \$\begingroup\$ Works, but also gives an error "RUNNING: 'VoI_Q(s' Missing arg to Repeat, evaling input.BAD EVAL STACK" \$\endgroup\$ – GolezTrol Sep 16 '16 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 '16 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\$
  • \$\begingroup\$ While my Lua solution is shorter (62 bytes) and is full program, your is far more creative. Good job! \$\endgroup\$ – val says Reinstate Monica Aug 1 '19 at 11:54
1
\$\begingroup\$

Julia, 42 bytes

h(s,l=1)=l==endof(s)?s:s*h(reverse(s),l+1)

Recursive function with counter variable l. If it is equal to the length of the string s, simply return it, otherwise concatenate (s*...) it with h(reverse(s),...) while incrementing the counter l+1.

\$\endgroup\$
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\$
  • \$\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\$ – Post Rock Garf Hunter Sep 18 '16 at 15:39
  • \$\begingroup\$ @WheatWizard Try this: try.haxe.org/#eE97b \$\endgroup\$ – Yytsi Sep 18 '16 at 15:44
  • \$\begingroup\$ Couldn't you split the string to an array of char and reverse that array? (if it's shorter...) \$\endgroup\$ – Paul Picard Sep 18 '16 at 16:53
  • \$\begingroup\$ @PaulPicard Tried that already, but it was longer :( \$\endgroup\$ – Yytsi Sep 18 '16 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 '16 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\$
  • \$\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 '18 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\$
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\$
  • \$\begingroup\$ can't use $++ here? \$\endgroup\$ – Ven Mar 21 '19 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 Mar 22 '19 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\$
  • \$\begingroup\$ 53 bytes. \$\endgroup\$ – Jonathan Frech Aug 12 '19 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\$ – Jonathan Frech Aug 12 '19 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\$ – Pandazoic Aug 12 '19 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\$ – Jonathan Frech Aug 12 '19 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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