Reverse stdin and place on stdout

58

7

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>

Thomas O

Posted 2011-01-30T12:09:55.137

Reputation: 3 044

Need I only support characters which can be input into the system executing the code? – Golden Ratio – 2017-03-03T11:34:01.000

Can we take input from the command line or as function arguments? – caird coinheringaahing – 2017-06-05T21:24:28.940

@ninjalj good idea for contest – Евгений Новиков – 2017-07-03T14:45:12.917

5Do you allow standard library functions like PHP strrev – Ming-Tang – 2011-01-31T06:46:15.853

Is the output allowed to put the input's last newline at the beginning instead of the end? – Joey Adams – 2011-02-02T18:33:21.780

@Joey Adams, yep, it should replicate the input exactly. – Thomas O – 2011-02-02T21:20:04.953

54Your example is somewhat wrong. The reverse of your input would be: ƃop ʎzɐʃ ǝɥʇ ɹǝʌo pǝdɯnɾ ǝH xoɟ uʍoɹq ʞɔınΌ ;-P – ninjalj – 2011-02-04T22:40:40.763

Answers

26

Golfscript - 3 chars

-1%

obfuscated version is also 3 chars

0(%

here is an explanation of how % works

gnibbler

Posted 2011-01-30T12:09:55.137

Reputation: 14 170

36So the second one is obfuscated but the first one isn't. Gotcha. – C0deH4cker – 2015-06-01T02:09:54.987

1@Thomas O SPOILER Working on a programming language that might compete with GolfScript. (It's like a 2D BrainF) This problem would stand as bdg; b - ask for input and write each character to the successor of the current cell, etc. d - reverses the entire strip. g - clear and output the strip. Too bad the language isn't done yet. – Conor O'Brien – 2015-09-29T01:10:03.213

9How can we ever compete with Golfscript?? – Thomas O – 2011-01-30T13:16:25.793

12@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. – Joey – 2011-01-30T13:24:13.717

@Joey, you missed my humour. – Thomas O – 2011-01-30T17:00:54.097

1@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. – Joey – 2011-01-30T18:16:47.420

3@Joey It was more a humourous despair as GolfScript seems like noise to the untrained eye. – Thomas O – 2011-01-30T18:31:49.490

45

Bash - 7

tac|rev

tac reverses line order, while rev reverses character order.

marcog

Posted 2011-01-30T12:09:55.137

Reputation: 10 244

I had rev|tac for the same score - just adding a note to say that this works for any POSIX shell, not just Bash. – Toby Speight – 2018-02-16T15:42:26.503

Let's just go the next step and alias that to a single letter bash command! alias z='tac|rev' – Daniel Standage – 2011-01-31T16:14:05.203

19@Diniel That's kinda the same as using compiler flags to define macros, i.e. against the spirit of code golf. – marcog – 2011-01-31T16:50:53.923

35

BrainFuck, 10 characters

,[>,]<[.<]

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

Kevin Brown

Posted 2011-01-30T12:09:55.137

Reputation: 5 756

2DNA 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. – ixtmixilix – 2012-12-18T09:35:07.153

10@ixtmixilix It actually just says something fundamental about stacks and reversing things. – Cruncher – 2013-12-06T16:56:29.183

23

C, 37 bytes

main(_){write(read(0,&_,1)&&main());}

Quixotic

Posted 2011-01-30T12:09:55.137

Reputation: 2 199

Cool, but it doesn't work for me. – Joey Adams – 2011-03-18T04:33:28.640

@Joey Adams:Try it out here.

– Quixotic – 2011-03-19T01:06:55.467

Ah, I had to compile without optimization. – Joey Adams – 2011-04-27T16:59:04.577

Doesn't work for me. – S.S. Anne – 2019-12-28T15:10:07.783

21

Haskell - 21

main=interact reverse

Konstantin

Posted 2011-01-30T12:09:55.137

Reputation: 211

3Not only short, but completely idiomatic as well :) – hammar – 2011-06-11T21:27:30.330

16

Python, 41 40 bytes

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

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

Probably could be optimised!

Thomas O

Posted 2011-01-30T12:09:55.137

Reputation: 3 044

1So print raw_input()[::~0]]? It's still Python 2 because of print – CalculatorFeline – 2016-04-04T02:58:13.770

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 – user8397947 – 2016-06-12T13:17:56.027

I wish I had an easy way of reversing something in PowerShell ;-) – Joey – 2011-01-30T12:28:11.657

6Martian people, always useful. [::-1] – Wok – 2011-02-04T16:16:25.857

16

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

Justin

Posted 2011-01-30T12:09:55.137

Reputation: 19 757

13

APL, 2

⊖⍞

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

jpjacobs

Posted 2011-01-30T12:09:55.137

Reputation: 3 440

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'.

– Adám – 2016-02-29T18:42:34.147

^^^^ Winner ^^^^ – CalculatorFeline – 2016-04-04T03:00:12.083

@Nᴮᶻ: well, the spec said to get the input from stdin, not from a string literal :) – jpjacobs – 2016-05-17T19:11:30.117

@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. – Adám – 2016-05-17T20:01:28.463

11

Perl - 23

print scalar reverse <>

Andrew

Posted 2011-01-30T12:09:55.137

Reputation: 271

6In fact, print"".reverse<> is only 17 chars. And with Perl 5.10+ you can save two more chars by using say instead of print. – Ilmari Karonen – 2012-04-29T15:05:49.967

6You can remove the third space. – Timwi – 2011-03-09T01:37:50.717

4I know this is very old, but you could also do: print~~reverse<> for 16 chars – Dom Hastings – 2013-12-14T09:59:53.063

5@DomHastings And with Perl 5.10+, say~~reverse<> would work? 14 chars. – Timtech – 2013-12-31T16:12:35.873

10

Ruby - 19 characters

puts$<.read.reverse

Nemo157

Posted 2011-01-30T12:09:55.137

Reputation: 1 891

10

C - 47 characters

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

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

Joey Adams

Posted 2011-01-30T12:09:55.137

Reputation: 9 929

2Does C evaluate numbers as booleans? If so, c>=0 can become ~c – Cyoce – 2016-04-04T06:36:46.340

1Just your idea but this saves 2-3 key strokes:main(c){(c=getchar())>0&&main(),putchar(c);} – Quixotic – 2011-03-09T05:51:34.300

Simply Awesome! – st0le – 2011-02-04T16:57:10.937

9

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.

Joey

Posted 2011-01-30T12:09:55.137

Reputation: 12 260

-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. – colsw – 2017-03-06T13:28:50.507

@ConnorLSW: That doesn't even read from stdin. And $input is an enumerator yielding lines, so you can't stringize it like that. – Joey – 2017-03-06T13:31:58.067

8

Perl 5.1, 14

say~~reverse<>

Timtech

Posted 2011-01-30T12:09:55.137

Reputation: 12 038

8

Befunge-93 - 11x2 (22 characters)

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

Tested using this interpreter.

MiffTheFox

Posted 2011-01-30T12:09:55.137

Reputation: 631

1not always :P – clap – 2015-09-14T23:52:52.277

19Are you sure you didn't just press random keys on your keyboard? – Thomas O – 2011-02-02T21:57:45.327

@Thomas - Are you sure you didn't try using the linked interpreter? It's web-based, in case you were worried about downloading anything. – MiffTheFox – 2011-02-02T22:08:20.453

4I'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. – Thomas O – 2011-02-02T22:11:23.393

7

Binary Lambda Calculus - 9 bytes

16 46 80 17 3E F0 B7 B0 40

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

C0deH4cker

Posted 2011-01-30T12:09:55.137

Reputation: 352

Know any good places to learn BLC? It looks like such a fun language! – phase – 2015-07-14T02:15:05.807

1

@phase This looks useful if you can handle the amount of logic theory there: https://tromp.github.io/cl/LC.pdf

– C0deH4cker – 2015-07-26T10:56:11.213

6

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.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

lol why does this remind me of minecraft? – don bright – 2015-06-01T01:23:11.570

Wow, and I thought my implementation in the language samples was the shortest at 16 chars. Impressive! – C0deH4cker – 2015-06-01T02:16:00.660

6

><>, 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=?;!

cole

Posted 2011-01-30T12:09:55.137

Reputation: 3 526

2-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 ; – Jo King – 2018-01-16T11:59:08.727

1@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. – cole – 2018-01-16T16:22:02.760

1

Hmm, actually this works just as well for 13 bytes (can't believe I missed the easy swap of 0=? to ?!)

– Jo King – 2018-04-20T05:07:20.367

@JoKing -1 Byte The ? character checks the stack top if 0 so then comparison with the length isn't needed, just the l.

– Teal pelican – 2019-08-20T12:03:10.243

@TealPelican Yes, I mentioned that in my second comment – Jo King – 2019-08-20T14:33:32.923

5

PHP - 38 17 characters

<?=strrev(`cat`);

Arnaud Le Blanc

Posted 2011-01-30T12:09:55.137

Reputation: 2 286

What is cat?? – Xanderhall – 2016-11-30T17:56:40.167

1@Xanderhall probably reads from stdin – Pavel – 2016-11-30T18:48:46.960

5

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.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

4

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.

FlipTack

Posted 2011-01-30T12:09:55.137

Reputation: 13 242

4

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.

FireFly

Posted 2011-01-30T12:09:55.137

Reputation: 7 107

Here is a shorter version (10 chars): line 1: #v~ line 2::<,_@#. Funny that using j does not improve it here. – Justin – 2014-01-10T09:03:10.890

@Quincunx that's clever, using the IP direction as a kind of implicit negation. – FireFly – 2014-01-10T10:47:33.860

4

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.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

4

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.

Sp3000

Posted 2011-01-30T12:09:55.137

Reputation: 58 729

4

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

Kevin Brown

Posted 2011-01-30T12:09:55.137

Reputation: 5 756

Updated the limit to match the Python one below, I can't imagine anyone using that much though. – Kevin Brown – 2011-02-06T16:09:08.063

One problem: fgets(STDIN) only reads the first line. – PleaseStand – 2011-02-01T00:09:20.877

Updated the code to now read all of the lines. – Kevin Brown – 2011-02-05T01:52:29.950

Except you have an artificial limit of 1000 chars – anonymous coward – 2011-02-05T09:55:30.727

4

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

kirbyfan64sos

Posted 2011-01-30T12:09:55.137

Reputation: 8 730

2Doesn't match the spec, unfortunately--the order of the lines needs to be reversed as well. – DLosc – 2015-06-01T01:23:21.813

Fk_.z_k I'm sure someone can get something shorter than this, but that's what i got. – gcq – 2015-06-01T13:32:48.280

@gcq I have a shorter version (5 chars), but I haven't gotten a chance to edit it. – kirbyfan64sos – 2015-06-01T17:07:30.147

@DLosc Fixed! I just read all the input, joined via newlines, and reversed that. – kirbyfan64sos – 2015-06-01T22:49:02.673

@FryAmTheEggman Ah, yes! Didn't know about that when I had posted this a few months back. – kirbyfan64sos – 2015-10-23T18:54:52.713

4

05AB1E, 1 byte

R

R reverses the input.

penalosa

Posted 2011-01-30T12:09:55.137

Reputation: 505

1Thanks for using 05AB1E :). You don't need the , at the end, because the top of the stack is printed automatically when nothing has printed. – Adnan – 2016-04-26T21:13:48.227

@Adnan Thanks for the tip. – penalosa – 2016-04-26T21:36:58.523

3

GameMaker Language, 90 89 82 Characters

No built-in reverse functions.

s=r=argument0;for(l=string_length(r);i<r;i++){c=string_char_at(s,l-i)o+=c}return o

Compile with all uninitialized variables as 0

Timtech

Posted 2011-01-30T12:09:55.137

Reputation: 12 038

Link to this language? – MD XF – 2017-09-19T03:31:05.703

@MDXF You can download Game Maker 8.1 Lite or the free version of GM Studio if you want to try this out. – Timtech – 2017-09-19T11:57:00.293

3

PHP - 44 characters

<?=strrev(file_get_contents('php://stdin'));

ircmaxell

Posted 2011-01-30T12:09:55.137

Reputation: 897

3

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.

BrainSteel

Posted 2011-01-30T12:09:55.137

Reputation: 5 132

3

Perl

print scalar reverse for reverse(<STDIN>);

huntar

Posted 2011-01-30T12:09:55.137

Reputation: 131

3

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.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

3

Fuzzy Octo Guacamole, 2 bytes

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

^z

^ gets input, z reverses, and implicit output.

Rɪᴋᴇʀ

Posted 2011-01-30T12:09:55.137

Reputation: 7 410

1Can 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) – Downgoat – 2016-04-04T04:00:27.640

@Downgoat groans but decides to edit anyway – Rɪᴋᴇʀ – 2016-04-04T04:01:52.213

Linked to the github. – Rɪᴋᴇʀ – 2016-04-04T04:02:21.887

1thanks. I'd upvote but I've already upvoted – Downgoat – 2016-04-04T04:02:50.780

2

Excel VBA, 18 + 1 = 19 Bytes

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

Code:

?StrReverse([A1])

+1 for ' before input in cell A1 (allows for handling strings that begin with '=')

Taylor Scott

Posted 2011-01-30T12:09:55.137

Reputation: 6 709

2

Perl 6, 16 bytes

print slurp.flip

slurp reads the input as a single string, and flip reverses it.

say is more common for output, but that introduces an extra newline that wasn't in the input.

Sean

Posted 2011-01-30T12:09:55.137

Reputation: 4 136

2

Brain-Flak, 15 bytes (non-competing)

{({}<>)<>}<>

Try it online!

12 bytes of code, and +3 bytes for the -c flag, which enables input and output in ASCII.

Explanation:

#While the stack is not empty:
{

 #Push the top of the stack onto the alternate stack
 ({}<>)

 #Toggle back to the main stack
 <>

#endwhile
}

#Toggle to the alternate stack, implicitly display
<>

James

Posted 2011-01-30T12:09:55.137

Reputation: 54 537

3Just curious, why is -c counted as 3 bytes? – ETHproductions – 2017-01-05T23:35:25.957

2

Japt, 1 byte

w

Try it online!

Oliver

Posted 2011-01-30T12:09:55.137

Reputation: 7 160

2

Commodore 64/VIC-20 BASIC, 48 BASIC bytes used

Here's a one-liner that will solve this issue:

0 INPUTA$:FORI=1TOLEN(A$):B$=MID$(A$,I,1)+B$:NEXT:PRINTA$":"B$

and here's how it looks on a Commodore 64 (more or less):

Reverse a string in Commodore BASIC

This will work on PETs and the C16/+4 series as well as the C128

Shaun Bebbers

Posted 2011-01-30T12:09:55.137

Reputation: 1 814

2

Whitespace, 67 bytes

This program requires a null byte to mark the end of input as Whitespace has no way to detect when stdin is empty. If you're using the TIO link make sure not to delete the last character in the input field (looks like a space) as it's a null byte. If you do you'll need to append a null byte using your browsers console.

   

  	
 
 	
	  
 			
	 
   	
	   
 
	

  
   	
	  	 
 				
  
 


Try it online!

Explanation

(s - space, t - tab, n - newline)

sssn  ; push 0 to use as the starting heap address
nsstn ; label 'read-loop'
sns   ; dup
tnts  ; getchar and store at address n
sns   ; dup
ttt   ; retrieve the character value we just read
ntsn  ; jez 'output-loop' - if it was a null byte switch to output
ssstn ; push 1
tsss  ; add - increment n
nsntn ; jmp 'read-loop'
nssn  ; label 'output-loop'
ssstn ; push 1
tsst  ; sub - decrement n
sns   ; dup
ttt   ; retrieve the character value at address n
tnss  ; putchar - display the character
nsnn  ; jmp 'output-loop'

Whitespace uses a stack and a heap for data storage. As I/O commands write to the heap naturally we store the string on the heap and keep the stack for our counter.

This program reads characters one at a time and stores them in order starting from heap address 0 counting up. Once the program reads a null byte it starts displaying characters starting from the previous heap address counting down. For the input hello\0 this populates the heap as [#0:h,#1:e,#2:l,#3:l,#4:o,#5:\0] then outputs the characters at addresses #4,#3,#2,#1,#0 and we end up with olleh.

Ephphatha

Posted 2011-01-30T12:09:55.137

Reputation: 581

2

Scala - 60

print(io.Source.fromInputStream(System.in).mkString.reverse)

Piotr Kolaczkowski

Posted 2011-01-30T12:09:55.137

Reputation: 131

2

Groovy 44 characters

args.reverse().each{print it.reverse()+" "}

Espen Schulstad

Posted 2011-01-30T12:09:55.137

Reputation: 441

2

Brachylog, 1 bytes

(maybe noncompeting?)

Try it online!

DanTheMan

Posted 2011-01-30T12:09:55.137

Reputation: 3 140

2

Common Lisp, 67 bytes

(do((a))((push(or(read-char()())(return(coerce a'string)))a)))

Try it online!

Renzo

Posted 2011-01-30T12:09:55.137

Reputation: 2 260

2

R, 41 bytes

cat(intToUtf8(rev(utf8ToInt(scan(,"")))))

Try it online!

Alternate "classic" version working directly with characters:

R, 53 bytes

for(i in rev(el(strsplit(scan(,""),split=""))))cat(i)

Try it online!

Because every question deserves at least one answer in R. Even string questions...

JayCe

Posted 2011-01-30T12:09:55.137

Reputation: 2 655

2

Keg, 1 byte

?

Try it online!

Print reversed input implicitly

Lyxal

Posted 2011-01-30T12:09:55.137

Reputation: 5 253

Doesn't work if there's any newlines in the input – Jo King – 2019-10-27T12:05:42.757

2

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

user85052

Posted 2011-01-30T12:09:55.137

Reputation:

2

Python - 35 chars

import os;print os.read(0,2e9)[::-1]

gnibbler

Posted 2011-01-30T12:09:55.137

Reputation: 14 170

os.read(0,-1) if work 1 char shorter – AMK – 2013-09-18T15:38:08.810

This is limited to 1e9 characters, though... not technically unlimited. – Thomas O – 2011-01-30T13:15:52.487

2It's not even legal Python, it lacks an argument to os.read(). Should be os.read(0,...) – hallvabo – 2011-01-30T15:55:00.840

@hallvabo, oops you are correct, should be 35 chars.9e9 doesn't work because it is too big to be converted to an int, so 2e9 is as high as it can go. – gnibbler – 2011-01-30T20:44:44.067

what about sys.maxint? – Thomas O – 2011-01-30T20:46:34.237

@Thomas, then I have to import sys, so it's way more characters! – gnibbler – 2011-01-30T20:53:55.943

1@gnibbler: import os,sys is possible. Even os.sys.maxint works for me (might be version/system dependent). – hallvabo – 2011-01-30T21:16:31.763

@hallvabo, yeah 64bit python doesn't like it :) – gnibbler – 2011-01-30T21:58:40.020

This only works in Python <=2.6. – nyuszika7h – 2014-06-23T11:38:19.900

2

C++ - 168 chars

#include<algorithm>
#include<iostream>
#include<string>
using namespace std;main(){string m;for(string l;getline(cin,l);)m+=l+"\n";reverse(m.begin(),m.end());cout<<m;}

grokus

Posted 2011-01-30T12:09:55.137

Reputation: 1 043

Can't you #define s string or something like that?or declare m and l at the same time? – Behrooz – 2013-10-06T20:05:05.703

2

Java, 165 156 bytes

class R{public static void main(String[]a){System.out.print(new StringBuilder(new java.util.Scanner(System.in).nextLine().replace("\\n","\n")).reverse());}}

Requires you to escape any line breaks in the input, but otherwise it works.

SuperJedi224

Posted 2011-01-30T12:09:55.137

Reputation: 11 342

I know it's quite a while since you've answered this question, but you can golf two things: StringBuilder->StringBuffer and you can removed the space at "\\n","\n" (-2 bytes). – Kevin Cruijssen – 2017-03-03T10:35:58.897

Bringing this back from the dead again! This program cannot handle newlines, which means it isn't a correct submission. The easiest way to fix this would be to have the Scanner read the whole file in one token by setting its delimiter to \A or \z (see Patterns), then invoking next.

– Jakob – 2017-08-15T00:46:05.623

2

Minkolang 0.10, 6 bytes (non-competitive)

This language was created after this challenge, but not for this challenge.

$or$O.

$o reads in all of the input as characters, r reverses the stack, $O outputs the whole stack as characters, and . stops the program. Try it here.

El'endia Starman

Posted 2011-01-30T12:09:55.137

Reputation: 14 504

2

AppleScript, 81 Bytes

Yeah. I'm amused by the "concision", too.

(display dialog""default answer"")'s text returned's characters's reverse as text

It grabs input from the user from STDIN equivalent (since it's not a terminal based language) and outputs the reverse. Simplez.

Addison Crump

Posted 2011-01-30T12:09:55.137

Reputation: 10 763

2

MarioLANG, 35 31 27 bytes

,)<.-<
+=">="
>[!([!
==#==#

Try it online!

I'm not sure if a MarioLANG interpreter existed prior to this challenge, but the esolangs page has been around since 2009 with information describing the language.

There are 2 main loops here. The first one, consisting of the first 3 columns, loads all the characters into memory (incrememnted by 1 for properly handing eof) The second loop, consisting of the last 3 columns, prints the data on the tape from right to left (along with decrementing the values so they display properly). I did some clever trickery to have these loops directly next to each other.

Zwei

Posted 2011-01-30T12:09:55.137

Reputation: 484

1

Java, 103 bytes

Full programs in Java suck.

class A{public static void main(String args[]){System.out.print(new StringBuffer(args[0]).reverse());}}

Xanderhall

Posted 2011-01-30T12:09:55.137

Reputation: 1 236

2Can't you change it from args to a? – FlipTack – 2016-12-26T14:20:14.433

FlipTack suggestion will save you 6 bytes, giving us a double digit Java solution. – NonlinearFruit – 2017-02-20T16:57:40.443

Your submission doesn't read from standard in, which, while not a violation of the body of the question, is a violation of the question title and the spirit of the question. – Jakob – 2017-08-15T00:49:02.183

1

awk, 24 bytes

Field separator set to '' means that each char is in its own field and we can use NF as iterator from end to begining. To break record barriers, RS is also '' meaning record ends at first empty record (\n\n).

{for(;NF-->0;)printf$NF}

Execution ends in an error as the NF-- reaches -1 and awk can't handle that. It could be handled with 2 more bytes to change the for(;NF-->0;) to for(;NF>0;NF--). Test it:

$ awk -F '' -v RS='' '{for(;NF-->0;)printf$NF}' file
od yzal eht revo depmuj eH
xof nworb kciuQawk: cmd. line:1: (FILENAME=asd FNR=1) fatal: NF set to negative value

James Brown

Posted 2011-01-30T12:09:55.137

Reputation: 663

1

SmileBASIC, 36 32 bytes

INPUT S$WHILE""<S$?POP(S$);
WEND

Bonus: add ATTR 2 between S$ and WHILE to display the inputted text rotated 180 degrees.

12Me21

Posted 2011-01-30T12:09:55.137

Reputation: 6 110

1

ZX81 BASIC 74 Bytes 71 Bytes (listing)

 1 LET B$=""
 2 INPUT A$
 3 FOR I=1 TO LEN A$
 4 LET B$=A$(I)+B$
 5 NEXT I
 6 PRINT A$;":";B$

You enter a string, which is stored in the variable A$; each character in A$ is transferred to the empty string B$, but is copied to B$ in reverse order (thanks to Dr Beep for the top tip).

Output is as follows:

ZX81 String Reverse

Actual bytes can be saved by using more typing - this takes up less room in the ZX81 RAM but is longer:

ZX81 longer less bytes listing

Note that this listing is the original entry; Using the function VAL or dividing PI into PI is a byte-saving tip, i.e., FOR I=PI/PI TO LEN A$

So to do code golf properly on a ZX81, you need longer listings as a rule of thumb.

Shaun Bebbers

Posted 2011-01-30T12:09:55.137

Reputation: 1 814

1

Alice, 7 bytes

\oi
/R@

Try it online!

Explanation

\    Reflect to SE. Switch to Ordinal.
R    Reverse top string on stack, does nothing.
     Reflect off bottom boundary --> move NE.
i    Read all input as a single string.
     Reflect off corner --> move back SW.
R    Reverse top string on stack, reverses input.
     Reflect off bottom boundary --> move NW.
\    Reflect to S. Switch to Cardinal.
/    Reflect to NE. Switch to Ordinal.
o    Print reversed output.
     Reflect off top boundary --> move SE.
@    Terminate the program.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

I'm having trouble understanding the control flow here. So the IP moves in a SE direction to R. And then it wraps around to i. But how does it go from i to R is the IP still is moving in a SE direction? – user41805 – 2017-04-12T08:18:47.923

@KritixiLithos In Alice, when in ordinal mode (moving along diagonals) the IP doesn't wrap around, it reflects instead. So after the first R it reflects against the bottom edge and goes to NE, runs i and then reflects against the corner and turns around towards SW, encountering the R again. – Leo – 2017-04-12T08:40:18.780

@KritixiLithos What Leo said. I got a bit lazy with this explanation and skipped all the boundary reflections. So in short, in Cardinal mode, the IP does wrap around, but in Ordinal mode, the boundaries are solid and the IP bounces like a light ray in a box. I added in all of the direction changes now. – Martin Ender – 2017-04-12T08:45:41.520

1

MarioLANG, 136 91 bytes

>,----------[!(>[.[([!
"============#="=====#
!) ++++++++++< !     <
#============" #====="

Reverses a string ending in a newline (\n)

Example:

Hello World!

becomes

!dlroW olleH

NOTE: Only works on linux or mac. Doesn't work in TIO either.

user69335

Posted 2011-01-30T12:09:55.137

Reputation:

1

JavaScript - 44

I don't think you can get much shorter with JS. Nothing interesting here.

alert(prompt().split('').reverse().join(''))

tristin

Posted 2011-01-30T12:09:55.137

Reputation: 189

1You can save 7 bytes with some ES6: alert([...prompt()].reverse().join``) – andrewarchi – 2017-06-15T04:34:43.093

1

JavaScript - 50 48 47

Slightly longer than the other JS entry

a='';for(i=(b=prompt()).length;i;a+=b[i---1]);a

Professor Allman

Posted 2011-01-30T12:09:55.137

Reputation: 261

1

Aceto, 3 bytes

r~p
r reads input
~ reverses it
p prints it

Try it online!

FantaC

Posted 2011-01-30T12:09:55.137

Reputation: 1 425

1

Julia 0.6, 33 bytes

print(reverse(readstring(STDIN)))

Try it online!

gggg

Posted 2011-01-30T12:09:55.137

Reputation: 1 715

1

Momema, 39 bytes

z00+1*0*0*-9z=+1**0y00+-1*0-9**0y=+-1*0

Try it online!

Explanation

                                                           #  i = 0
z    0       #  label z0: jump past label z0 (no-op)       #  do {
0    +1*0    #            [0] = [0] + 1                    #    i += 1
*0   *-9     #            [[0]] = read chr                 #    tape[i] = read chr
z    =+1**0  #  label z1: jump past label z(!([[0]] + 1))  #  } while (tape[i] != -1)
y    0       #  label y0: jump past label y0 (no-op)       #  do {
0    +-1*0   #            [0] = [0] - 1                    #    i -= 1
-9   **0     #            print chr [[0]]                  #    print chr tape[i]
y    =+-1*0  #  label y1: jump past label y(!([0] - 1))    #  } while (i != 1)

Esolanging Fruit

Posted 2011-01-30T12:09:55.137

Reputation: 13 542

1

Attache, 22 bytes

Stdout!Reverse!Stdin[]

Try it online!

! calls a function using its right argument. This is equivalent to:

Stdout[Reverse[Stdin[]]]

I couldn't find a more clever solution for reversing or outputting, unfortunately.

Conor O'Brien

Posted 2011-01-30T12:09:55.137

Reputation: 36 228

Um – MD XF – 2018-02-19T00:45:24.987

@MDXF That has a trailing newline. – Conor O'Brien – 2018-02-19T00:49:37.423

I don't see in the challenge spec that that isn't allowed; it typically is with outputting. – MD XF – 2018-02-19T00:50:12.883

@MDXF I don't think the challenge could be more clear: reverse stdin and place on stdout. Not "reverse stdin, place on stdout, then place a newline for the heck of it." – Conor O'Brien – 2018-02-19T00:50:58.293

1

Shakespeare Programming Language, 213 185 bytes (153 bytes with error)

Thanks to Jo King for saving 28 bytes!

Try it online!

213-byte old version

(Whitespace added for readability only)

R.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Remember you.Open mind.Be you nicer I?
If solet usAct I.
Recall.Be you nicer I?
If sospeak thy.If sorecall.
If solet usAct I.

153-byte version that terminates in an error (Try it online!)

R.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Open mind.Be you nicer I?If soremember you.
If solet usAct I.
Recall.
Speak thy.
Let usAct I.

Explanation

Scene I is a reused loop. I use Jo King's own method to reuse Scene I, since jumping to Act I is shorter than jumping to Scene I. This is why I begin the scene with [Exeunt]. Then, Ajax tells Puck to push himself, so he pushes a 0 (all characters are initialized to 0). Now, Puck takes input (Open mind) and compares himself to Ajax, who remains at 0. If Puck's value is greater than 0, the scene loops. Thus, Puck pushes a 0 followed by the string, and then moves on to the next part when he encounters the terminating -1. In the second part, Puck pops a value and compares it to 0. If it is greater than 0, he prints it and pops a second value. He then returns to the beginning of the program. There, he pushes the value he just popped. He takes input, which will now be constantly -1, so he falls through back to the second half. This completes the loop.

In the error-terminating version, no 0 is initially pushed to mark the beginning of the string (end of the reversed string), so some things are re-ordered, and the checks for it are removed. The program eventually throws an error that Puck cannot recall anything.

Hello Goodbye

Posted 2011-01-30T12:09:55.137

Reputation: 442

I didn't think terminating in an error was appropriate. Nice job reusing Scene I. I considered it but wasn't able to do it. – Hello Goodbye – 2019-10-27T11:50:45.393

Ignoring STDERR is fine by default, and I don't see anything in the question stopping it. You can always include both versions in your answer – Jo King – 2019-10-27T12:02:09.440

I'll do that, thank you! – Hello Goodbye – 2019-10-27T12:58:31.743

1

C# - 116

using System.Linq;using c=System.Console;class p{static void Main(){c.Write(c.In.ReadToEnd().Reverse().ToArray());}}

snmcdonald

Posted 2011-01-30T12:09:55.137

Reputation: 641

1

VB.Net - 96

Module M
Sub Main()
Console.Write(CStr(ConsoleIn.ReadToEnd.Reverse.ToArray))
End Sub
End Module

90 (With Turned off Option Strict)

Module M
Sub Main()
Console.Write(Console.In.ReadToEnd.Reverse.ToArray)
End Sub
End Module

snmcdonald

Posted 2011-01-30T12:09:55.137

Reputation: 641

1

Retina 0.8.2, 24 bytes

Contains the unprintable DEL 0xFF character (delete) to use as a delimiter. These are located at the end of lines 2, 3, and 5, as well as between $1 and $2 on line 4.

$

+s`(.)(.*)
$2$1


Try it online!

mbomb007

Posted 2011-01-30T12:09:55.137

Reputation: 21 944

1

><>, 17 bytes

!vi:1+?
 ~
l<o;!?

I don't even need to reverse the input as putting it on a stack naturally does that.

Aaron

Posted 2011-01-30T12:09:55.137

Reputation: 3 689

1

Retina, 6 bytes

Non-competing, since Retina is newer than this challenge.

O$^s`.

Try it online!

With Retina's latest addition (sort stages), this became a lot shorter. Sort stages work by matching a bunch of things via the supplied regex, and then sorting those matches treating everything that wasn't matched like list-delimiters. This stage type comes with a bunch of options that we can (ab)use to reverse a string.

For a start, the regex is simply ., which matches a single character, and the s modifier ensures that it can also match linefeeds. That is, we're sorting all the characters in the input. As for the others:

  • O just activates sorting.
  • $ tells Retina that the matches shouldn't be sorted by their actual string value, but that a regex substitution is first applied to them, and they are then sorted by the result of that substitution. Now the program has only a single line (the substitution would go on the second line), so that all matches are just replaced with an empty string. That means, to the sorting function, all matches are equal, and no sorting happens at all.
  • Finally, ^ tells Retina to reverse the order of the matches after sorting.

Martin Ender

Posted 2011-01-30T12:09:55.137

Reputation: 184 808

1

Pyke, 1 byte (noncompetitive)

_

Try it here!

Blue

Posted 2011-01-30T12:09:55.137

Reputation: 26 661

0

tcl, 30

puts [string rev [read stdin]]

To terminate input press Ctrl+D.

Available to run on: https://goo.gl/18Sqz0

sergiol

Posted 2011-01-30T12:09:55.137

Reputation: 3 055

0

Jelly, 6 bytes

⁸ƈ;$ÐL

Try it online!

Erik the Outgolfer

Posted 2011-01-30T12:09:55.137

Reputation: 38 134

0

Triangular, 21 bytes

\.~/.?.`.<....p.]p@(<

Try it online!

This formats into the triangle:

     \
    . ~
   / . ?
  . ` . <
 . . . . p
. ] p @ ( <

This part:

   \
  . ~
 / . ?
. ` . <

creates a loop to continue reading input as long as it's not EOF. ? jumps over the directional command < that restarts the loop.

This part:

 . . . . p
. ] p @ ( <

pops the EOF from the stack, directs control flow to the left, opens a loop, prints the top of stack, pops it, and continues the loop if there are any values left.

MD XF

Posted 2011-01-30T12:09:55.137

Reputation: 11 605

If this is remarkably unclear, ping me and I'll fix it tomorrow. I'm tired. :P – MD XF – 2017-06-15T04:25:19.830

0

Braingolf, 4 bytes

&,&@

Try it online!

Possibly non-competing?

Another reverse builtin

Skidsdev

Posted 2011-01-30T12:09:55.137

Reputation: 9 656

0

8th, 7 bytes

Code

s:rev .

Example

ok> "Quick brown fox\nHe jumped over the lazy dog" s:rev .
god yzal eht revo depmuj eH
xof nworb kciuQ

Chaos Manor

Posted 2011-01-30T12:09:55.137

Reputation: 521

0

Chip, 59 bytes

))))))))-v~.
ABCDEFGHS<8<
01234567 >9s
))))))))~\t
abcdefgh

Try it online!

Requires either a null terminator, or the -z flag (which handles that for you). Since I use the flag only for the benefit of TIO, it is not included in the byte count.

ABCDEFGH            These are the eight bits of the input.

01234567            These are the eight bits of the stack head.

abcdefgh            These are the eight bits of the output.

))))))))-v~.        When at least one bit is on, enable writing to the stack
ABCDEFGHS<8<        (9) and suppress output (S). When all bits are zero,
         >9s        read from the stack (8) and suppress input (s) instead.

ABCDEFGH            When stack is in write mode, copy input bits directly
01234567            onto the stack.

01234567            When the stack is in read mode, send the values directly
))))))))~\t         to output. Once the stack is empty (all bits are zero),
abcdefgh            terminate the program (t).

Phlarx

Posted 2011-01-30T12:09:55.137

Reputation: 1 366

0

Implicit, 3 bytes

©®"

Try it online!

©    consume all input
 ®   reverse the stack
  "  stringify entire stack
     implicit output

For an alternate and faster version, use ©"\, which reads all input, stringifies it, and reverses the string. It's faster than reversing an entire stack.

Version without builtins:

(~.);(¸@;)
(~.);       read all input with each character incremented by 1
     (¸@;)  decrement each character, print, pop loop

MD XF

Posted 2011-01-30T12:09:55.137

Reputation: 11 605

0

QBIC, 28 bytes

{_?~A=B|_X\Z=_fA|+chr$(13)+Z

Explanation

I can't just grab a multi-line string off of the cmd line parameters with the ; command, that doesn't work in QBasic. Also, when we ask the user for input with _? it terminates on enter. We work around that with a loop:

{          DO infinitely
_?         Ask the user for input, store it in A$
~A=B       IF A$ is empty (or equal to B$ which is unassigned and therefore == '')
|_X        THEN QUIT, and print Z$ on the way out
\Z=+Z      ELSE set Z to be
_fA|       The last line entered reversed
+chr$(13)  Plus a newline
+Z         plus whatever already was in Z$
           The IF and the DO-loop are closed implicitly

steenbergh

Posted 2011-01-30T12:09:55.137

Reputation: 7 772

0

K (oK), 12 bytes

Solution:

`0:||:'"\n"\

Try it online!

Example:

`0:||:'"\n"\"Quick brown fox\nHe jumped over the lazy dog";
god yzal eht revo depmuj eH
xof nworb kciuQ

Explanation:

We can't easily take STDIN, so take a string, split on newline, reverse each line and then reverse the list of lines before printing to STDOUT:

`0:||:'"\n"\ / the solution
       "\n"\ / split (\) on newline "\n"
    |:'      / reverse (|:) each (')
   |         / reverse (|)
`0:          / print to STDOUT

streetster

Posted 2011-01-30T12:09:55.137

Reputation: 3 635

0

Forked, 32 bytes

v
>-v
| ~&-:-v
| |  | !
\-:-p^-<

Try it online!

The first block is the same as in the 44-byte solution. The second changes a bit direction-wise:

   &-:-v
     | !
    p^-<

Still fairly self-explanatory once you read the 44-byte explanation.


Forked, 44 bytes

v     &<
>-v    |
| ~  >-:
| |  | |
^-:-p^!<

Try it online!

I love how self-explanatory this language is. However, I'll still explain it, as the conditional structure is a bit complex.

The first block thingy reads all input to the stack:

>-v
| ~
| |
^-:-

The fork at the bottom : directs the instruction pointer West if the inputted character is > 0, causing it to go back into the loop. When EOF is entered, it directs it East, causing it to enter the second block thingy:

      &<
       |
     >-:
     | |
    p^!<

First, it pops the EOF character. Then it goes North, then West, then hits the fork. While the top of stack is nonzero (i.e. it exists), the fork directs the IP South, then the < immediately directs it West, hitting ! (print as character and pop), and it goes back into the loop. The fork directs the IP North if it's zero (i.e. the stack is empty), where it hits < and then & (exit, in this scenario). (note that the redirect is entirely unnecessary but the bytecount is the same, so... whatever.)

MD XF

Posted 2011-01-30T12:09:55.137

Reputation: 11 605

0

Add++, 32 bytes

x:1
y:''
Wx,]getchar,`y,x+,`x
oy

Try it online!

Fairly basic, although STDIN support was recently added to Add++, so I decided to show it off.

First, we set the two variables we need:

x:1
y:''

x to the integer 1 and y to the empty string. Next, we loop over each character in STDIN:

Wx,]getchar,`y,x+,`x

This is a while loop, with the condition simply being x. Each , denotes the separation of a new command, so the code is expanded into

Wx,
  ]getchar
  `y
  x+
  `x

]getchar is an additional, Add++ jargon for an extended command that is prefixed with a ]. Here, it simply reads a character from STDIN and assigns that to x. If the end of STDIN is reached, an empty string is returned.

Next, with

`y
x+
`x

We prepend this character to y, effectively building the string in reverse.

Once all input has been read, the x variable contains the empty string, and the while loop is terminated. Then we reach the final command

oy

This uses prefix notation: o is the command, and y indicates the variable to operate here. Here, o means output, without a trailing newline. y contains the input reversed, so this outputs our final result.

user81017

Posted 2011-01-30T12:09:55.137

Reputation:

0

Pepe, 16 bytes

REEeREEEEeEeeReee

Try it online! (Compiler makes whitespaces when doing links between e and r)

Explanation:

REEeREEEEeEeeReee - full program

REEe              - insert input as string
    REEEEeEee     - reverse whole stack
             Reee - output

u_ndefined

Posted 2011-01-30T12:09:55.137

Reputation: 1 253

0

Ahead,  9  13 bytes

~ilj~#
 >dko@

This one will function properly when NULs are on the input.

Try it online!

snail_

Posted 2011-01-30T12:09:55.137

Reputation: 1 982

0

PowerShell, 38 bytes

Thanks to Joey for the $($input) expression.

$($input)-join'
'|% t*y|%{$s=$_+$s}
$s

Try it online!


Alternative, 38 bytes

@($input)-join'
'|% t*y|%{$s=$_+$s}
$s

Try it online!

mazzy

Posted 2011-01-30T12:09:55.137

Reputation: 4 832

0

Pip, 3 bytes

RVq

Try it online!

Kenneth Taylor

Posted 2011-01-30T12:09:55.137

Reputation: 183

0

Brain-Flak, 12 bytes

{({}<>)<>}<>

Not going to be winning with this, but it works

Try it Online!

EdgyNerd

Posted 2011-01-30T12:09:55.137

Reputation: 1 106

0

Rust, 57 bytes

fn q(s:&str)->String{s.chars().rev().collect::<String>()}

Try it online!

Dart, 34 bytes

f(s)=>s.split('').reversed.join();

Try it online!

Pretty convoluted, you have to get a String List then reverse it and join it back for it to work.

Elcan

Posted 2011-01-30T12:09:55.137

Reputation: 913

0

Triangular, 14 bytes

(\~(#vp]<./)?<

Try it online!

I am almost 100% certain that ,~#n^`>p/ (9 bytes) would work if IP switches behaved in accordance with their specification, but in the meantime, 14 ain't too shabby.

Ungolfed:

     ( 
    \ ~ 
   ( # v 
  p ] < .
 / ) ? <
----------------------------------------------
(                Set a point for the IP to jump to
 ~v<             Read a character from input, change directions twice
    ?)/          ) returns to the previously set point. ? will skip the jump back if ToS < 0
       p(        Pop the top value of the stack (the null-input), then set a new jump point
         /#<[    Pop the top value of the stack and print that value, then jump back if ToS > 0

Reinstate Monica

Posted 2011-01-30T12:09:55.137

Reputation: 1 382

0

Elixir, 42 bytes

IO.puts String.reverse IO.read :stdio,:all

Vasu Adari

Posted 2011-01-30T12:09:55.137

Reputation: 941

0

Poetic, 60 bytes

normally i create a reversal
so could i?i suppose maybe i do

Try it online!

This is actually slightly modified from an example on my website. The only things changed are that the letters are now stored right to left instead of left to right, the 11 letter word is replaced with two 1-letter words, and there is no 0 command at the end (which results in an error, but that's okay).

JosiahRyanW

Posted 2011-01-30T12:09:55.137

Reputation: 2 600

0

Python 2, 39 bytes

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

TheInitializer

Posted 2011-01-30T12:09:55.137

Reputation: 829

1import sys;print sys.stdin.read()[::-1] is shorter. – Mego – 2016-04-04T05:37:19.143

0

Matlab (56)

a=1;b=0;while(a)a=input('','s');b=[flipud(a) 10 b];end,b

Execution:

abc
def


b =


fed
cba

Abr001am

Posted 2011-01-30T12:09:55.137

Reputation: 862

I believe [flip(a),10,b] should work? – Stewie Griffin – 2017-11-02T13:19:42.097

@StewieGriffin Yes seemingly. – Abr001am – 2017-11-02T16:41:43.580

0

TI-BASIC, 43 (+ 7 = 50, for Input statement)

If you count : as TI's ‘newline’...

Programs show similarity to this, and are thus attributed to the site (too lazy to be involved in copyright infringement, etc.).

V2 (with input ‘STDIN’, 50)

PROGRAM:R
Input Str1
Str1
For(I,1,length(Ans)-1
sub(Ans,2I,1)+Ans
End
sub(Ans,1,I

V2 (no input, 43)

Called as "string":prgmR.

PROGRAM:R
For(I,1,length(Ans)-1
sub(Ans,2I,1)+Ans
End
sub(Ans,1,I

Conor O'Brien

Posted 2011-01-30T12:09:55.137

Reputation: 36 228

@ThomasKwa Oh lookie there. No, it was a program I already made one day during class. I thought it would be kinda cool to reverse a string, so I got this. It did take a lot of thought, though I had help from some python code I found (I forgot where.) Seeing as the two are so similar (eek!) I should probably give credit anyhow, as not to tick anyone off over there. – Conor O'Brien – 2015-09-29T02:11:41.050

0

Hassium, 62 Bytes

func main(){s=input();for(x=s.length- 1;x>=0;print(s[x--]))0;}

Run and see expanded here

Jacob Misirian

Posted 2011-01-30T12:09:55.137

Reputation: 737

0

Javascript (ES6), 37

Really simple. Try below in Firefox.

alert([...prompt()].reverse().join``)

, 4 chars / 8 bytes (noncompetitive)

ôᴙï)

Try it here (Firefox only).

Mama Fun Roll

Posted 2011-01-30T12:09:55.137

Reputation: 7 234

0

CJam, 19

(non-competitive)

1q]e_{_1#0=}{)\}w;;

This is the first golfing language I've tried to learn, and I just started learning it. It's pretty crazy, but it works in the online interpreter. Try it here.

Explanation (It's very hard for me to explain it, maybe someone can help):

1q]        #e  puts a 1 and the text input into an array
e_         #e  flatten the array
{_1#0=}    #e  check if if the 1 is at the beginning of our array. If true, we keep looping. The trick is once the array is destroyed, we are applying the # operator on 1 not the array, in which case it is a power operator, so it's (1)^(1), which is 1, not 0. Yeah it's ridiculous.
{)\}w      #e  in the body of the while loop we pop the last element off of the array and put it onto the stack. 
;;         #e  then we need to get rid of the 1 so we pop the top element off the stack. I'm not sure why we need to do this twice.

geokavel

Posted 2011-01-30T12:09:55.137

Reputation: 6 352

qW% is a bit shorter. :) By the way, this challenge predates CJam's creation by a few years, so it's customary to include a note in the post stating that the submission is non-competing. – Dennis – 2015-11-03T06:03:21.883

Oh, I see: take every -1st. Very clever, thank you! – geokavel – 2015-11-03T16:19:37.983

0

Seriously, 2 bytes (non-competitive)

R

There is a formfeed character (ASCII 0x0C) as the first byte. Hexdump (reversible with xxd -r):

00000000: 0c52                                     .R

Try it online! (note that the formfeed shows up as the dingbat on TIO - one of the nice features Dennis has added is the parsing of CP437 dingbats into ASCII control codes).

Mego

Posted 2011-01-30T12:09:55.137

Reputation: 32 998

0

Tellurium, 5 bytes (non-competing)

i&r.^
  • The i command gets input and stores it in the selected cell.
  • & starts string manipulation mode.
  • r is a string mode command. It reverses whatever is stored in the selected cell.
  • . exits string mode.
  • ^ outputs the cell's value.

m654

Posted 2011-01-30T12:09:55.137

Reputation: 765

0

Hexagony, 28 bytes (Non-competitive)

Compressed:

.$@.>;<..\'"/$\$/}{,<..>.../

Try it Online!

X88B88

Posted 2011-01-30T12:09:55.137

Reputation: 91

It seems this would stop reading input on null-bytes. You can fix this by incrementing the character after reading it (but before the branch) and decrementing it again before printing (but after the branch that checks for termination). – Martin Ender – 2016-08-13T20:09:26.793

0

Sesos, 3 bytes (non-competing)

x

Since this contains unprintables, here is a hexdump:

0000000: 788c19                                            x..

This is the code that was used to generate it:

fwd 1,jnz,rwd 1,jmp,put,rwd 1

Try it online!

This works, provided the input does not contain null characters (\0).
UTF-8 locale as far as I'm aware.

Explanation:

      ;(implicit nop) Start the input loop.
fwd 1 ;Store the input character for subsequent use.
jnz   ;(implicit jne) Store an input character. If EOF is reached, terminate input.
rwd 1 ;Let the output loop start.
jmp   ;Start the output loop.
put   ;Output a character.
rwd 1 ;Go to the next character.
      ;(implicit jnz) If the character is null (terminator), exit.

Erik the Outgolfer

Posted 2011-01-30T12:09:55.137

Reputation: 38 134