58
\$\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\$
  • 5
    \$\begingroup\$ Do you allow standard library functions like PHP strrev \$\endgroup\$ – Ming-Tang Jan 31 '11 at 6:46
  • \$\begingroup\$ Is the output allowed to put the input's last newline at the beginning instead of the end? \$\endgroup\$ – Joey Adams Feb 2 '11 at 18:33
  • \$\begingroup\$ @Joey Adams, yep, it should replicate the input exactly. \$\endgroup\$ – Thomas O Feb 2 '11 at 21:20
  • 51
    \$\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 '11 at 22:40
  • \$\begingroup\$ Need I only support characters which can be input into the system executing the code? \$\endgroup\$ – Golden Ratio Mar 3 '17 at 11:34

94 Answers 94

25
\$\begingroup\$

Golfscript - 3 chars

-1%

obfuscated version is also 3 chars

0(%

here is an explanation of how % works

\$\endgroup\$
  • 9
    \$\begingroup\$ How can we ever compete with Golfscript?? \$\endgroup\$ – Thomas O Jan 30 '11 at 13:16
  • 11
    \$\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 '11 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 '11 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 '11 at 18:31
  • 32
    \$\begingroup\$ So the second one is obfuscated but the first one isn't. Gotcha. \$\endgroup\$ – C0deH4cker Jun 1 '15 at 2:09
44
\$\begingroup\$

Bash - 7

tac|rev

tac reverses line order, while rev reverses character order.

\$\endgroup\$
  • \$\begingroup\$ Let's just go the next step and alias that to a single letter bash command! alias z='tac|rev' \$\endgroup\$ – Daniel Standage Jan 31 '11 at 16:14
  • 17
    \$\begingroup\$ @Diniel That's kinda the same as using compiler flags to define macros, i.e. against the spirit of code golf. \$\endgroup\$ – marcog Jan 31 '11 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\$ – Toby Speight Feb 16 '18 at 15:42
35
\$\begingroup\$

BrainFuck, 10 characters

,[>,]<[.<]

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

\$\endgroup\$
  • 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 '12 at 9:35
  • 8
    \$\begingroup\$ @ixtmixilix It actually just says something fundamental about stacks and reversing things. \$\endgroup\$ – Cruncher Dec 6 '13 at 16:56
23
\$\begingroup\$

C, 37 bytes

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

Haskell - 21

main=interact reverse
\$\endgroup\$
  • 3
    \$\begingroup\$ Not only short, but completely idiomatic as well :) \$\endgroup\$ – hammar Jun 11 '11 at 21:27
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\$
  • \$\begingroup\$ I wish I had an easy way of reversing something in PowerShell ;-) \$\endgroup\$ – Joey Jan 30 '11 at 12:28
  • 6
    \$\begingroup\$ Martian people, always useful. [::-1] \$\endgroup\$ – Wok Feb 4 '11 at 16:16
  • 1
    \$\begingroup\$ So print raw_input()[::~0]]? It's still Python 2 because of print \$\endgroup\$ – CalculatorFeline Apr 4 '16 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\$ – dorukayhan Jun 12 '16 at 13:17
15
\$\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\$
12
\$\begingroup\$

APL, 2

⊖⍞

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

\$\endgroup\$
  • \$\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 '16 at 18:42
  • \$\begingroup\$ ^^^^ Winner ^^^^ \$\endgroup\$ – CalculatorFeline Apr 4 '16 at 3:00
  • \$\begingroup\$ @Nᴮᶻ: well, the spec said to get the input from stdin, not from a string literal :) \$\endgroup\$ – jpjacobs May 17 '16 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 '16 at 20:01
11
\$\begingroup\$

Perl - 23

print scalar reverse <>
\$\endgroup\$
  • 6
    \$\begingroup\$ You can remove the third space. \$\endgroup\$ – Timwi Mar 9 '11 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\$ – Ilmari Karonen Apr 29 '12 at 15:05
  • 4
    \$\begingroup\$ I know this is very old, but you could also do: print~~reverse<> for 16 chars \$\endgroup\$ – Dom Hastings Dec 14 '13 at 9:59
  • 5
    \$\begingroup\$ @DomHastings And with Perl 5.10+, say~~reverse<> would work? 14 chars. \$\endgroup\$ – Timtech Dec 31 '13 at 16:12
10
\$\begingroup\$

Ruby - 19 characters

puts$<.read.reverse
\$\endgroup\$
10
\$\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\$
  • \$\begingroup\$ Simply Awesome! \$\endgroup\$ – st0le Feb 4 '11 at 16:57
  • 1
    \$\begingroup\$ Just your idea but this saves 2-3 key strokes:main(c){(c=getchar())>0&&main(),putchar(c);} \$\endgroup\$ – Quixotic Mar 9 '11 at 5:51
  • 2
    \$\begingroup\$ Does C evaluate numbers as booleans? If so, c>=0 can become ~c \$\endgroup\$ – Cyoce Apr 4 '16 at 6:36
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\$
  • \$\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 '17 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 '17 at 13:31
8
\$\begingroup\$

Perl 5.1, 14

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

Befunge-93 - 11x2 (22 characters)

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

Tested using this interpreter.

\$\endgroup\$
  • 19
    \$\begingroup\$ Are you sure you didn't just press random keys on your keyboard? \$\endgroup\$ – Thomas O Feb 2 '11 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 '11 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 '11 at 22:11
  • 1
    \$\begingroup\$ not always :P \$\endgroup\$ – clap Sep 14 '15 at 23:52
7
\$\begingroup\$

Binary Lambda Calculus - 9 bytes

16 46 80 17 3E F0 B7 B0 40

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

\$\endgroup\$
  • \$\begingroup\$ Know any good places to learn BLC? It looks like such a fun language! \$\endgroup\$ – phase Jul 14 '15 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 '15 at 10:56
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\$
  • \$\begingroup\$ lol why does this remind me of minecraft? \$\endgroup\$ – don bright Jun 1 '15 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 '15 at 2:16
6
\$\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\$
  • 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 '18 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 '18 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 '18 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\$ – Teal pelican 6 hours ago
  • \$\begingroup\$ @TealPelican Yes, I mentioned that in my second comment \$\endgroup\$ – Jo King 4 hours ago
5
\$\begingroup\$

PHP - 38 17 characters

<?=strrev(`cat`);
\$\endgroup\$
  • \$\begingroup\$ What is cat?? \$\endgroup\$ – Xanderhall Nov 30 '16 at 17:56
  • 1
    \$\begingroup\$ @Xanderhall probably reads from stdin \$\endgroup\$ – Pavel Nov 30 '16 at 18:48
5
\$\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\$
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\$
  • \$\begingroup\$ One problem: fgets(STDIN) only reads the first line. \$\endgroup\$ – PleaseStand Feb 1 '11 at 0:09
  • \$\begingroup\$ Updated the code to now read all of the lines. \$\endgroup\$ – Kevin Brown Feb 5 '11 at 1:52
  • \$\begingroup\$ Except you have an artificial limit of 1000 chars \$\endgroup\$ – anonymous coward Feb 5 '11 at 9:55
  • \$\begingroup\$ Updated the limit to match the Python one below, I can't imagine anyone using that much though. \$\endgroup\$ – Kevin Brown Feb 6 '11 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\$
  • \$\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 '14 at 9:03
  • \$\begingroup\$ @Quincunx that's clever, using the IP direction as a kind of implicit negation. \$\endgroup\$ – FireFly Jan 10 '14 at 10:47
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\$
  • 2
    \$\begingroup\$ Doesn't match the spec, unfortunately--the order of the lines needs to be reversed as well. \$\endgroup\$ – DLosc Jun 1 '15 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 '15 at 13:32
  • \$\begingroup\$ @gcq I have a shorter version (5 chars), but I haven't gotten a chance to edit it. \$\endgroup\$ – kirbyfan64sos Jun 1 '15 at 17:07
  • \$\begingroup\$ @DLosc Fixed! I just read all the input, joined via newlines, and reversed that. \$\endgroup\$ – kirbyfan64sos Jun 1 '15 at 22:49
  • \$\begingroup\$ @FryAmTheEggman Ah, yes! Didn't know about that when I had posted this a few months back. \$\endgroup\$ – kirbyfan64sos Oct 23 '15 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\$

05AB1E, 1 byte

R

R reverses the input.

\$\endgroup\$
  • 1
    \$\begingroup\$ Thanks for using 05AB1E :). You don't need the , at the end, because the top of the stack is printed automatically when nothing has printed. \$\endgroup\$ – Adnan Apr 26 '16 at 21:13
  • \$\begingroup\$ @Adnan Thanks for the tip. \$\endgroup\$ – macleos Apr 26 '16 at 21:36
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\$
3
\$\begingroup\$

PHP - 44 characters

<?=strrev(file_get_contents('php://stdin'));
\$\endgroup\$
3
\$\begingroup\$

Perl

print scalar reverse for reverse(<STDIN>);
\$\endgroup\$
3
\$\begingroup\$

Fission, 20 15 bytes

KX$ \
!
SR?J%
~

The algorithm is very similar to Martin's, but the implementation differs significantly.

How it works

Everything starts at R, which releases an eastward atom with mass 1 and energy 0.

Upon hitting ?, an input character is saved as the atom's mass, and the energy is left at 0 unless stdin returns EOF, in which case energy becomes 1.

J is Fission's jump command, and jumps an atom forward a number of cells equivalent to its current energy, leaving the atom with 0 energy. For now, our atom has 0 energy and ignores this command.

We then strike %, which is a switch. With greater than 0 energy, our atom would be directed down (as if reflected by an \ mirror), but since we have exactly 0 energy, we are sent upwards by the opposite mirror, /.

Our atom continues until it strikes a second mirror, \ this time directing it left.

We increment the atom's energy to 1 with $, and use X to duplicate the atom. One copy will reflect back on to the $ command (leaving that copy with 2 energy) and the other copy will be pushed on to the stack, K.

Our reflected copy travels backwards from whence it came until it hits the % switch again. Now that we have a positive energy, we reflect as if we had hit an \ mirror, wrapping around the board onto the next S and decrementing our energy to 1.

The S command will consume 1 energy to preserve our direction. Had we no energy, the atom would have deflected as if struck by an \ mirror, downward. Instead, we move to the right again and pick up more input with ? and the cycle repeats.

Once our atom reaches EOF, the ? command will store 1 energy in the atom. Thus, when we hit the J command this time, we completely skip over the % switch and land on the S switch with 0 energy.

Now, since our energy was consumed in the jump, our direction is not preserved by the S switch, but we are rather directed downward. We then decrement our energy to -1 with the ~ command and wrap around the board. When hit with a negative energy, the K command pops an atom instead of pushing one. We output our newly popped atom with !, and use the 1 energy of that atom to bypass the S switch, and the cycle completes.

If the stack K was empty, our atom's energy is negated (resulting in +1 energy) and it is reflected back onto the ~ command, leaving it with energy 0. Upon hitting S again, we are deflected to the right, until the ? is struck. Since EOF has been reached, the ? destroys the atom and terminates the program.

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

Labyrinth, 10 bytes

,)";@
:".(

Normally, Labyrinth programs are supposed to resemble mazes, but I was able to compress the loops in this one so tightly, that code ended up as a single block (room?). Here is a slightly expanded version which makes it easier to follow the control flow:

,""")""""""";""@
"   "   "   "
:""""   ."""(

, reads one byte at a time from STDIN until it hits EOF and returns -1. The ) increments this value so that we get something positive for each read byte and zero at EOF. The : duplicates each read byte.

Once we hit EOF, the instruction pointer proceeds to the second loop, where it repeatedly discards one value with ; (initially the EOF, later the second copy of each byte), then decrements the next value with ( and prints it with .. Due to that second copy (which is always positive) we know that the IP will take a right-turn at the top and continue in this loop.

After all bytes have been printed the top of the stack is zero again and the IP continues straight ahead to the @ and the program ends.

The seemingly unnecessary duplication of each byte is what allows me to ensure that (even in the tight loops of the golfed version) the IP always takes the correct turn and never crosses from one loop to the other.

A tip of the hat to TheNumberOne and Sp3000 whose own attempts helped a lot in finding this highly compressed solution.

\$\endgroup\$

protected by Community Jul 15 '18 at 4:23

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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