67
\$\begingroup\$

Requirements:

  • Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.)
  • Output the reverse of the input on stdout.

Example:

Input:

Quick brown fox
He jumped over the lazy dog

Output:

god yzal eht revo depmuj eH
xof nworb kciuQ

Shortest wins.

Leaderboard:

var QUESTION_ID=242,OVERRIDE_USER=61563;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\$
8
  • 5
    \$\begingroup\$ Do you allow standard library functions like PHP strrev \$\endgroup\$
    – Ming-Tang
    Jan 31, 2011 at 6:46
  • 1
    \$\begingroup\$ Is the output allowed to put the input's last newline at the beginning instead of the end? \$\endgroup\$
    – Joey Adams
    Feb 2, 2011 at 18:33
  • 1
    \$\begingroup\$ @Joey Adams, yep, it should replicate the input exactly. \$\endgroup\$
    – Thomas O
    Feb 2, 2011 at 21:20
  • 63
    \$\begingroup\$ Your example is somewhat wrong. The reverse of your input would be: ƃop ʎzɐʃ ǝɥʇ ɹǝʌo pǝdɯnɾ ǝH xoɟ uʍoɹq ʞɔınΌ ;-P \$\endgroup\$
    – ninjalj
    Feb 4, 2011 at 22:40
  • 3
    \$\begingroup\$ Your example is somewhat wrong. The reverse of your input would be: The slow purple fox She crawled below the diligent cat \$\endgroup\$ Aug 18, 2020 at 5:10

140 Answers 140

1
2 3 4 5
48
\$\begingroup\$

Bash - 7

tac|rev

tac reverses line order, while rev reverses character order.

\$\endgroup\$
3
  • \$\begingroup\$ Let's just go the next step and alias that to a single letter bash command! alias z='tac|rev' \$\endgroup\$ Jan 31, 2011 at 16:14
  • 20
    \$\begingroup\$ @Diniel That's kinda the same as using compiler flags to define macros, i.e. against the spirit of code golf. \$\endgroup\$
    – moinudin
    Jan 31, 2011 at 16:50
  • \$\begingroup\$ I had rev|tac for the same score - just adding a note to say that this works for any POSIX shell, not just Bash. \$\endgroup\$ Feb 16, 2018 at 15:42
36
\$\begingroup\$

BrainFuck, 10 characters

,[>,]<[.<]

Beats a good amount of answers for such a simple language.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ DNA reverses its order all the time, so maybe there's something fundamental about the nature of information and computation in what you have observed. I came across this solution while solving problems on rosalind.info with shell one-liners. \$\endgroup\$
    – ixtmixilix
    Dec 18, 2012 at 9:35
  • 11
    \$\begingroup\$ @ixtmixilix It actually just says something fundamental about stacks and reversing things. \$\endgroup\$
    – Cruncher
    Dec 6, 2013 at 16:56
26
\$\begingroup\$

Golfscript - 3 chars

-1%

obfuscated version is also 3 chars

0(%

here is an explanation of how % works

\$\endgroup\$
7
  • 9
    \$\begingroup\$ How can we ever compete with Golfscript?? \$\endgroup\$
    – Thomas O
    Jan 30, 2011 at 13:16
  • 14
    \$\begingroup\$ @Thomas: By using FlogScript, I guess. In any case, if you post a trivial task, then expect solutions to be equally trivial. And if it takes three method calls in Python, if can just as well be three characters in Golfscript. \$\endgroup\$
    – Joey
    Jan 30, 2011 at 13:24
  • 1
    \$\begingroup\$ @Thomas: Sorry, it wasn't that obvious. Given that some members already had quiet heated discussions about this very language that seemingly was no humor, it wasn't too unreasonably to assume similar here. \$\endgroup\$
    – Joey
    Jan 30, 2011 at 18:16
  • 3
    \$\begingroup\$ @Joey It was more a humourous despair as GolfScript seems like noise to the untrained eye. \$\endgroup\$
    – Thomas O
    Jan 30, 2011 at 18:31
  • 41
    \$\begingroup\$ So the second one is obfuscated but the first one isn't. Gotcha. \$\endgroup\$
    – C0deH4cker
    Jun 1, 2015 at 2:09
24
\$\begingroup\$

C, 37 bytes

main(_){write(read(0,&_,1)&&main());}
\$\endgroup\$
4
  • \$\begingroup\$ Cool, but it doesn't work for me. \$\endgroup\$
    – Joey Adams
    Mar 18, 2011 at 4:33
  • \$\begingroup\$ @Joey Adams:Try it out here. \$\endgroup\$
    – Quixotic
    Mar 19, 2011 at 1:06
  • \$\begingroup\$ Ah, I had to compile without optimization. \$\endgroup\$
    – Joey Adams
    Apr 27, 2011 at 16:59
  • \$\begingroup\$ Doesn't work for me. \$\endgroup\$
    – S.S. Anne
    Dec 28, 2019 at 15:10
22
\$\begingroup\$

Haskell - 21

main=interact reverse
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Not only short, but completely idiomatic as well :) \$\endgroup\$
    – hammar
    Jun 11, 2011 at 21:27
17
\$\begingroup\$

Pancake Stack, 342 316 bytes

Put this nice pancake on top!
[]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "".
Put this delightful pancake on top!
[#]
Eat the pancake on top!
Eat the pancake on top!
Show me a pancake!
Eat the pancake on top!
If the pancake is tasty, go over to "#".
Eat all of the pancakes!

It assumes that the input is terminated by a null character (^@ on commandline). Example run, using the interpreter:

Put this nice pancake on top!
[]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "".
Put this delightful pancake on top!
[#]
Eat the pancake on top!
Eat the pancake on top!
Show me a pancake!
Eat the pancake on top!
If the pancake is tasty, go over to "#".
Eat all of the pancakes!
~~~~~~~~~~~~~~~~~~~~~~~~
Hello, World!^@
!dlroW ,olleH
\$\endgroup\$
16
\$\begingroup\$

Python, 41 40 bytes

import sys;print sys.stdin.read()[::-1]

41 -> 40 - removed semicolon at end of program.

Probably could be optimised!

\$\endgroup\$
5
  • \$\begingroup\$ I wish I had an easy way of reversing something in PowerShell ;-) \$\endgroup\$
    – Joey
    Jan 30, 2011 at 12:28
  • 6
    \$\begingroup\$ Martian people, always useful. [::-1] \$\endgroup\$
    – Wok
    Feb 4, 2011 at 16:16
  • 1
    \$\begingroup\$ So print raw_input()[::~0]]? It's still Python 2 because of print \$\endgroup\$ Apr 4, 2016 at 2:58
  • \$\begingroup\$ Here's an code golf entry formatting tip. Always write the language you wrote the program with in this format: # Language Name, Character/Byte Count \$\endgroup\$
    – SE is dead
    Jun 12, 2016 at 13:17
  • \$\begingroup\$ You can use raw_input instead of sys.stdin.read \$\endgroup\$
    – nTerior
    Jan 22, 2021 at 16:21
14
\$\begingroup\$

APL, 2

⊖⍞

Or CircleBar QuoteQuad if the characters don't come through, simply meaning: reverse keyboard character input.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Halve your byte-count! You don't even need the . is a complete anonymous function that can be assigned and used: f←⌽ f 'The quick brown fox'. \$\endgroup\$
    – Adám
    Feb 29, 2016 at 18:42
  • \$\begingroup\$ ^^^^ Winner ^^^^ \$\endgroup\$ Apr 4, 2016 at 3:00
  • \$\begingroup\$ @Nᴮᶻ: well, the spec said to get the input from stdin, not from a string literal :) \$\endgroup\$
    – jpjacobs
    May 17, 2016 at 19:11
  • \$\begingroup\$ @jpjacobs Common PPGC practice is to allow inline argument instead of stdin for languages that do not support (or for which it is unnatural to use) stdin. \$\endgroup\$
    – Adám
    May 17, 2016 at 20:01
11
\$\begingroup\$

Perl - 23

print scalar reverse <>
\$\endgroup\$
4
  • 6
    \$\begingroup\$ You can remove the third space. \$\endgroup\$
    – Timwi
    Mar 9, 2011 at 1:37
  • 6
    \$\begingroup\$ In fact, print"".reverse<> is only 17 chars. And with Perl 5.10+ you can save two more chars by using say instead of print. \$\endgroup\$ Apr 29, 2012 at 15:05
  • 4
    \$\begingroup\$ I know this is very old, but you could also do: print~~reverse<> for 16 chars \$\endgroup\$ Dec 14, 2013 at 9:59
  • 5
    \$\begingroup\$ @DomHastings And with Perl 5.10+, say~~reverse<> would work? 14 chars. \$\endgroup\$
    – Timtech
    Dec 31, 2013 at 16:12
11
\$\begingroup\$

C - 47 characters

main(c){if(c=getchar(),c>=0)main(),putchar(c);}

Note that this uses O(n) stack space. Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Simply Awesome! \$\endgroup\$
    – st0le
    Feb 4, 2011 at 16:57
  • 2
    \$\begingroup\$ Just your idea but this saves 2-3 key strokes:main(c){(c=getchar())>0&&main(),putchar(c);} \$\endgroup\$
    – Quixotic
    Mar 9, 2011 at 5:51
  • 3
    \$\begingroup\$ Does C evaluate numbers as booleans? If so, c>=0 can become ~c \$\endgroup\$
    – Cyoce
    Apr 4, 2016 at 6:36
10
\$\begingroup\$

Ruby - 19 characters

puts$<.read.reverse
\$\endgroup\$
1
  • \$\begingroup\$ puts`dd`.reverse \$\endgroup\$
    – TKirishima
    Oct 10, 2022 at 20:12
10
\$\begingroup\$

Binary Lambda Calculus - 9 bytes

16 46 80 17 3E F0 B7 B0 40

Source: http://ioccc.org/2012/tromp/hint.html

\$\endgroup\$
2
  • \$\begingroup\$ Know any good places to learn BLC? It looks like such a fun language! \$\endgroup\$
    – jado
    Jul 14, 2015 at 2:15
  • 1
    \$\begingroup\$ @phase This looks useful if you can handle the amount of logic theory there: tromp.github.io/cl/LC.pdf \$\endgroup\$
    – C0deH4cker
    Jul 26, 2015 at 10:56
9
\$\begingroup\$

Windows PowerShell, 53 54

-join($x=[char[]]($($input)-join'
'))[($x.count)..0]

2011-01-30 (54) – First attempt

2011-01-30 (53) – Inline line breaks are fun.

2011-01-3- (52) – Inlined variable assignments too.

\$\endgroup\$
2
  • \$\begingroup\$ -join($a="$args")[$a.Length..0] on its own seems to work for the provided example, I don't have any issues with the linebreaks running with windows crlf - not sure about psv2 or whatever you used when this was written. \$\endgroup\$
    – colsw
    Mar 6, 2017 at 13:28
  • \$\begingroup\$ @ConnorLSW: That doesn't even read from stdin. And $input is an enumerator yielding lines, so you can't stringize it like that. \$\endgroup\$
    – Joey
    Mar 6, 2017 at 13:31
9
\$\begingroup\$

Perl 5.1, 14

say~~reverse<>
\$\endgroup\$
8
\$\begingroup\$

Befunge-93 - 11x2 (22 characters)

>~:0`v >:v
^    _$^,_@

Tested using this interpreter.

\$\endgroup\$
4
  • 19
    \$\begingroup\$ Are you sure you didn't just press random keys on your keyboard? \$\endgroup\$
    – Thomas O
    Feb 2, 2011 at 21:57
  • \$\begingroup\$ @Thomas - Are you sure you didn't try using the linked interpreter? It's web-based, in case you were worried about downloading anything. \$\endgroup\$
    – MiffTheFox
    Feb 2, 2011 at 22:08
  • 4
    \$\begingroup\$ I'm only joking. I'm sure it will work, but it just looks like you pressed some keys randomly. That indicates a very compact language. \$\endgroup\$
    – Thomas O
    Feb 2, 2011 at 22:11
  • 1
    \$\begingroup\$ not always :P \$\endgroup\$
    – clapp
    Sep 14, 2015 at 23:52
7
\$\begingroup\$

><>, 16 14 bytes

-2 bytes by @JoKing

two years (!) later, removes the extra -1 from reading input by shifting around the logic for halting.

i:0(7$.
0=?;ol

Try it online!

Similar to the other ><> answer, this doesn't need to reverse the stack because of the way input is read in the first line. I'm actually not too sure whether or not this should be a suggestion for the other ><> answer, as it is quite different in appearance but similar in concept.

The main difference is that my answer compares the input to 0, and if it is less (i.e. there is no input -- i returns -1 if there is no input) it jumps to (1,7), if not, (0,7). If it jumps to the former, it pops the top value (-1) and starts a print loop. If it jumps to the latter, it continues the input loop.

11 bytes, exits with an error

Courtesy of @JoKing

i:0(7$.
~o!

Try it online!

I believe this is valid now via meta consensus.

Previous answer (14 bytes)

i:0(7$.
~ol0=?;!
\$\endgroup\$
5
  • 2
    \$\begingroup\$ -5 bytes by ending with an error. Otherwise -2 bytes (errors on empty input). Also the original errors on empty input, which can be fixed by moving the o after the ; \$\endgroup\$
    – Jo King
    Jan 16, 2018 at 11:59
  • 1
    \$\begingroup\$ @JoKing Good catch on the o part; didn't notice that at the time. And thanks for the save. Clever use of the comparison to zero to get rid of the last -1. \$\endgroup\$
    – cole
    Jan 16, 2018 at 16:22
  • 1
    \$\begingroup\$ Hmm, actually this works just as well for 13 bytes (can't believe I missed the easy swap of 0=? to ?!) \$\endgroup\$
    – Jo King
    Apr 20, 2018 at 5:07
  • \$\begingroup\$ @JoKing -1 Byte The ? character checks the stack top if 0 so then comparison with the length isn't needed, just the l. \$\endgroup\$ Aug 20, 2019 at 12:03
  • \$\begingroup\$ @TealPelican Yes, I mentioned that in my second comment \$\endgroup\$
    – Jo King
    Aug 20, 2019 at 14:33
6
\$\begingroup\$

Fission, 16 14 12 bytes

DY$\
?
[Z~K!

Explanation

Control flow starts at D with a down-going (1,0) atom. The ? reads from STDIN, one character at a time, setting the mass to the read character code and the energy to 0. Once we hit EOF, ? will instead set the energy to 1. The [ redirects the atom onto a Z switch. As long as we're reading characters, the energy will be 0, so the atom is deflected to the upwards by the Z. We clone the atom, looping one copy back into the ? to keep reading input. We increment the other copy's energy to 1 with $ and push it onto the stack K. So the input loop is this:

DY$\
?
[Z K

When the energy is 1 due to EOF, the Z will instead let the atom pass straight through and decrement the energy to 0 again. ~ decrements the energy further to -1. Atoms with negative energy pop from the stack, so we can retrieve the characters in opposite order and print them with !. Now note that the grid is toroidal, so the atom reappears on the left edge of the same row. Remember that we incremented the energy of the pushed atoms earlier with $, so the atoms now have energy 1 just like the last output from ? and will again pass straight through the Z. The path after EOF is therefore

?
[Z~K!

This loop on the bottom row continues until the stack is empty. When that happens, the atom is reflected back from the K and its energy becomes positive (+1). The ~ decrements it once more (moving to the left), so that we now hit the Z with non-positive energy. This deflects the atom downward, such that it ends up in the wedge of Y where it's stored, and because there are no more moving atoms, the program terminates.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ lol why does this remind me of minecraft? \$\endgroup\$
    – don bright
    Jun 1, 2015 at 1:23
  • \$\begingroup\$ Wow, and I thought my implementation in the language samples was the shortest at 16 chars. Impressive! \$\endgroup\$
    – C0deH4cker
    Jun 1, 2015 at 2:16
6
\$\begingroup\$

Stack Cats, 7 bytes

<!]T[!>

Try it online!

There's a bunch of alternatives for the same byte count, most of which are essentially equivalent in how they work:

Explanation

A short Stack Cats primer:

  • Every program has to have mirror symmetry, and by mirroring any piece of code we obtain new code which computes the inverse function. Therefore the last three characters of the program above undo the first three, if it wasn't for the command in the centre.
  • The memory model is an infinite tape of stacks, which hold an implicit, infinite amount of zeros at the bottom. The initial stack has a -1 on top of those zeros and then the input bytes on top of that (with the first byte at the very top and the last byte above the -1).
  • For output, we simply take the final stack, discard a -1 at the bottom if there is one, and then print all the values as bytes to STDOUT.

Now for the actual program:

<    Move the tape head one stack left (onto an empty stack).
!    Bitwise NOT of the implicit zero on top, giving -1.
]    Move back to the original stack, taking the -1 with the tape head.
     We're now back to the original situation, except that we have a -1
     on top.
T    Reverse the stack down to the -1 at the bottom. One of the reasons
     we needed to move a -1 on top is that T only works when the top of
     the stack is nonzero. Since the first byte of the input could have
     been a null-byte we need the -1 to make sure this does anything at
     all.
[    Push the -1 to the stack on the left.
!    Bitwise NOT, turning it back into 0 (this is irrelevant).
>    Move the tape head back onto the original stack.

Sp3000 set his brute force search to find all other 7-byte solutions, so here are some alternatives:

<]!T![>
>![T]!<
>[!T!]<

These three variants are essentially the same, except that they differ in when the bitwise NOT is computed and whether we use the empty stack on the left or on the right.

<]T!T[>
>[T!T]<

Like I said in the explanation above, T doesn't do anything when the top of the stack is zero. That means we can actually put the ! in the middle instead. That means the first T is a no-op, then we turn the zero on top into a -1 and then then second T performs the reversal. Of course, this means that the final memory state has a -1 on the stack next to the original one, but that doesn't matter since only the stack at the current tape head position affects the output.

<*ITI*>

This variant uses * (XOR 1) instead of !, so that it turns the zero into +1, and the I is a conditional push which pushes positive values and right, negative values left, and negates them in either case (such that we still end up with a -1 on top of the original stack when we encounter T), so this ultimately works the same as the original <!]T[!> solution.

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

PHP - 38 17 characters

<?=strrev(`cat`);
\$\endgroup\$
3
  • \$\begingroup\$ What is cat?? \$\endgroup\$
    – Xanderhall
    Nov 30, 2016 at 17:56
  • 1
    \$\begingroup\$ @Xanderhall probably reads from stdin \$\endgroup\$
    – Pavel
    Nov 30, 2016 at 18:48
  • \$\begingroup\$ <?=strrev(`dd`); is better \$\endgroup\$
    – TKirishima
    Oct 10, 2022 at 20:11
5
\$\begingroup\$

Fuzzy Octo Guacamole, 2 bytes

(non-competing, FOG is newer than the challenge)

^z

^ gets input, z reverses, and implicit output.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Can you add a link to the language? I'm trying to navigate to the language's github but it's very FOGgy (ba dum tsh) \$\endgroup\$
    – Downgoat
    Apr 4, 2016 at 4:00
  • \$\begingroup\$ @Downgoat groans but decides to edit anyway \$\endgroup\$
    – Riker
    Apr 4, 2016 at 4:01
  • \$\begingroup\$ Linked to the github. \$\endgroup\$
    – Riker
    Apr 4, 2016 at 4:02
  • 1
    \$\begingroup\$ thanks. I'd upvote but I've already upvoted \$\endgroup\$
    – Downgoat
    Apr 4, 2016 at 4:02
5
\$\begingroup\$

Hexagony, 16 bytes

\{\{:}($.,.=;)$\

Try it online!

Expanded: (Made with Hexagony Colorer)

Reverse Cat in Hexagony

Explanation:

  • Blue path moves IP to the red path
  • Red path moves "forward" in memory, reads a byte from STDIN, and increments it by 1, then checks if it's positive. The increment is so that the check will pass for all values including null bytes, and only fail for EOF (which Hexagony reads as negative 1)
  • Orange path is reached when the check fails, it reverses memory and then puts the IP on the green path
  • Green path goes back through the memory, attempting to divide 0 by each byte in memory. If the byte is empty, the end of the string has been reached, and the program crashes attempting to divide by zero. Otherwise it decrements the byte by 1 (to undo the increment from before) and prints it as a character.

Alternative 21 byte solutions that properly terminate instead of crashing:

\{}\(//,;./')"<$|/$/@

and

},)<>'"<{\@..(_$.>.$;

\$\endgroup\$
4
\$\begingroup\$

PHP, 82 29 24 29 28 characters

<?=strrev(fread(STDIN,2e9));

82 -> 29: The new line character is preserved when reversed with strrev.
29 -> 24: Uses the shortcut syntax now
24 -> 29: Now reads all lines instead of a single line

\$\endgroup\$
4
  • \$\begingroup\$ One problem: fgets(STDIN) only reads the first line. \$\endgroup\$ Feb 1, 2011 at 0:09
  • \$\begingroup\$ Updated the code to now read all of the lines. \$\endgroup\$ Feb 5, 2011 at 1:52
  • \$\begingroup\$ Except you have an artificial limit of 1000 chars \$\endgroup\$ Feb 5, 2011 at 9:55
  • \$\begingroup\$ Updated the limit to match the Python one below, I can't imagine anyone using that much though. \$\endgroup\$ Feb 6, 2011 at 16:09
4
\$\begingroup\$

Befunge-98 - 11 10

#v~
:<,_@#

(Tested with cfunge)

The variant below breaks the requirement slightly: it performs the task but outputs an infinite stream of null bytes afterwards (and doesn't terminate).

~#,

The way it works is that it repeatedly reads input to the stack (~) one character at a time, jumping over (#) the comma. When EOF is reached, ~ acts as a reflector and the PC flips over, repeatedly popping and outputting a character (,) while jumping over (#) the tilde.

\$\endgroup\$
3
  • \$\begingroup\$ Here is a shorter version (10 chars): line 1: #v~ line 2::<,_@#. Funny that using j does not improve it here. \$\endgroup\$
    – Justin
    Jan 10, 2014 at 9:03
  • \$\begingroup\$ @Quincunx that's clever, using the IP direction as a kind of implicit negation. \$\endgroup\$
    – FireFly
    Jan 10, 2014 at 10:47
  • \$\begingroup\$ Late to the party, I know, but you can do this on a single line with jump-overs to save a byte: ~;,_@#:;# \$\endgroup\$ Jul 20, 2023 at 3:29
4
\$\begingroup\$

Pyth - 3 5 4 bytes

So, the original 3-char version didn't reverse the line order, just the lines. I then came up with this 5-char version:

_jb.z

I saved 1 byte thanks to @FryAmTheEggman to result it:

_j.z

Live demo.

Explanation:

  .w  read all the input into a list of strings
 j    join (j) by using a newline character
_     reverse the result
      Pyth implicitly prints the result on an expression

Original (incorrect) solution:

This technically doesn't count because Pyth was created in 2014, but it's still neat that it's tied with GolfScript.

#_w

Explanation:

#    loop while no errors
  w  read a line of input (throws an error on end-of-file or Control-C)
 _   reverse the input line
     Pyth implicitly prints the result on an expression
\$\endgroup\$
5
  • 2
    \$\begingroup\$ Doesn't match the spec, unfortunately--the order of the lines needs to be reversed as well. \$\endgroup\$
    – DLosc
    Jun 1, 2015 at 1:23
  • \$\begingroup\$ Fk_.z_k I'm sure someone can get something shorter than this, but that's what i got. \$\endgroup\$
    – gcq
    Jun 1, 2015 at 13:32
  • \$\begingroup\$ @gcq I have a shorter version (5 chars), but I haven't gotten a chance to edit it. \$\endgroup\$ Jun 1, 2015 at 17:07
  • \$\begingroup\$ @DLosc Fixed! I just read all the input, joined via newlines, and reversed that. \$\endgroup\$ Jun 1, 2015 at 22:49
  • \$\begingroup\$ @FryAmTheEggman Ah, yes! Didn't know about that when I had posted this a few months back. \$\endgroup\$ Oct 23, 2015 at 18:54
4
\$\begingroup\$

Cubix, 9 8 bytes

Many thanks to Martin Ender for this golf:

w;o@i.?\

See it work online!

This becomes the following cube (> indicates initial instruction pointer):

      w ;
      o @
> i . ? \ . . . .
  . . . . . . . .
      . .
      . .

The first step of the program is to take all input. i puts 1 byte of input onto the stack. Unless the input is finished, ? makes the IP turn right, wrapping around the cube until it reaches w, which sends it back to i.

When input finishes, the ? makes the IP head north, entering the output loop:

  • o: print the character at the top of the stack
  • w: 'sidestep' the pointer to the right
  • ;: pop the character that was just printed
  • \: reflect the IP, sending it East
  • ?: if there are chars left to print, turn right, back into the loop.

The final time ? is hit, when nothing is left on the stack, the IP continues forward instead:

  • i: take a byte of input. This will be -1 as input has finished.
  • \: reflect the IP, sending it North, into:
  • @: terminate the program.

9 byte solution

..o;i?@!/

See it work online!

In cube form:

      . .
      o ;
> i ? @ ! / . . .
  . . . . . . . .
      . .
      . .

The first character encoutered is i, which takes a charcode of input. If there is no input left, this is -1.

The next character is ? - a decision. If the top of stack is positive, it turns right, wrapping around the cube until it hits / which sends it back to the i, creating an input loop. However, if the TOS is negative, input has finished, and so it turns left into the output loop.

The output loop is simple. o; outputs and pops the TOS. The first time this is run, -1 is the top of stack, but does not map to a character and is therefore ignored. / reflects the IP to move left, where it encounters !@ - which terminates the program if the stack is empty. Otherwise, the IP continues, hitting ? again - because the stack is not empty, the TOS must be a charcode, all of which are positive1, so this makes the IP turn right and continue the output loop.


1 Both solutions assume that the input will not contain null bytes.

\$\endgroup\$
4
\$\begingroup\$

Wumpus, 12 bytes

i=)!4*0.l&o@

Try it online!


Martin's answer showcases Wumpus' triangular grid control flow well, but I thought I'd give this challenge a try with a one-liner.

The easier to understand version (one byte longer) is:

i=)!8*0.;l&o@

which works like so:

[Input loop]
i        Read a byte of input (gives -1 on EOF)
=)!      Duplicate, increment then logical not (i.e. push 1 if EOF, else 0)
8*       Multiply by 8 (= x)
0        Push 0 (= y)
.        Jump to (x, y), i.e. (8, 0) if EOF else (0, 0) to continue input loop 

[Output]
;        Pop the extraneous -1 at the top from EOF
l&o      Output <length of stack> times
@        Terminate the program

Now let's take a look at the golfed version, which differs in the middle:

i=)!4*0.l&o@

The golfed version saves a byte by not needing an explicit command ; to pop the extraneous -1. On EOF, this program jumps to (4, 0) instead of (8, 0) where it executes 4*0. again — except this time the extraneous -1 is on top! This causes us to jump to (-4, 0), which due to wrapping is the same as (8, 0) for this grid, getting us where we want whilst consuming the extraneous value at the same time.

\$\endgroup\$
4
\$\begingroup\$

Wumpus, 13 11 bytes

)?\;l&o@
=i

Try it online!

Explanation

Since Wumpus is a stack-based language, the basic idea is to read all STDIN to the stack and then just print the entire stack from top to bottom. The interesting part here is the control flow through the grid.

To understand the control flow, we need to look at the actual triangular grid layout:

enter image description here

The IP starts in the top left corner going east. We can see that there's a loop through the group of six cells on the left, and a branch off of the \. As you might expect, the loop reads all input, and the linear section at the end writes the result back to STDOUT.

Let's look at the loop first. It makes more sense to think of the first )?\ as not being part of the loop, with the actual loop beginning at the i. So here's the initial bit:

)   Increment an implicit zero to get a 1.
?\  Pop the 1 (which is truthy) and execute the \, which reflects the IP
    to move southwest.

Then the loop starts:

i   Read one byte from STDIN and push it to the stack (or -1 at EOF).
    Note that Wumpus's grid doesn't wrap around, instead the IP reflects
    off the bottom edge.
=   Duplicate the byte we've read, so that we can use it for the condition
    later without losing it.
)   Increment. EOF becomes zero (falsy) and everything else positive (truthy).
?\  If the incremented value is non-zero, execute the \ again, which 
    continues the loop. Otherwise (at EOF), the \ is skipped and the
    IP keeps moving east.

That leaves the linear section at the end:

;   Get rid of the -1 we read at EOF.
l   Push the stack depth, i.e. the number of bytes we've read.
&o  Print that many bytes.
\$\endgroup\$
4
\$\begingroup\$

Wren, 40 33 bytes

After I discovered a really clever trick...

Fn.new{|a|System.write(a[-1..0])}

Try it online!

Wren, 53 bytes

Wren has no STDIN functions... I guess I will just be using a function instead of hard-coding the value and using a snippet (which is a bit risky).

Fn.new{|a|[-1..-a.count].each{|w|System.print(a[w])}}

TIO

Explanation

Fn.new{                                               Create a new anonymous function (because Wren has no input functions)
       |a|                                            With the parameter a
          [-1..-a.count]                              Generate the range [-1,-2,...,len(a-1),len(a)]
                        .each                         Pass this range to the given function:
                             {|w|                     Take one parameter a
                                 System.print(a[w])}} And output it to STDOUT

Wren, 54 bytes

Fn.new{|a|
for(i in-1..-a.count)System.write(a[i])
}

TIO

\$\endgroup\$
4
\$\begingroup\$

Prolog (SWI), 31 bytes

a:-get0(C),C>0,a,put(C);!.
:-a.

Try it online!

\$\endgroup\$
3
\$\begingroup\$

PHP - 44 characters

<?=strrev(file_get_contents('php://stdin'));
\$\endgroup\$
1
2 3 4 5

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.