# Reverse stdin and place on stdout

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.

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

## Golfscript - 3 chars

-1%

obfuscated version is also 3 chars

0(%

here is an explanation of how % works

• How can we ever compete with Golfscript?? – Thomas O Jan 30 '11 at 13:16
• @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 Jan 30 '11 at 13:24
• @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 Jan 30 '11 at 18:16
• @Joey It was more a humourous despair as GolfScript seems like noise to the untrained eye. – Thomas O Jan 30 '11 at 18:31
• So the second one is obfuscated but the first one isn't. Gotcha. – C0deH4cker Jun 1 '15 at 2:09

## Bash - 7

tac|rev

tac reverses line order, while rev reverses character order.

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

## BrainFuck, 10 characters

,[>,]<[.<]

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

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

## C, 37 bytes

• Cool, but it doesn't work for me. – Joey Adams Mar 18 '11 at 4:33
• @Joey Adams:Try it out here. – Quixotic Mar 19 '11 at 1:06
• Ah, I had to compile without optimization. – Joey Adams Apr 27 '11 at 16:59
• Doesn't work for me. – S.S. Anne Dec 28 '19 at 15:10

main=interact reverse
• Not only short, but completely idiomatic as well :) – hammar Jun 11 '11 at 21:27

# Pancake Stack, 342 316 bytes

Put this nice pancake on top!
[]
Put this  pancake on top!
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!
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

# Python, 41 40 bytes

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

Probably could be optimised!

• I wish I had an easy way of reversing something in PowerShell ;-) – Joey Jan 30 '11 at 12:28
• Martian people, always useful. [::-1] – Wok Feb 4 '11 at 16:16
• So print raw_input()[::~0]]? It's still Python 2 because of print – CalculatorFeline Apr 4 '16 at 2:58
• 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 Jun 12 '16 at 13:17

## APL, 2

⊖⍞

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

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

## Perl - 23

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

## Ruby - 19 characters

puts$<.read.reverse # C - 47 characters main(c){if(c=getchar(),c>=0)main(),putchar(c);} Note that this uses O(n) stack space. Try it online! • Simply Awesome! – st0le Feb 4 '11 at 16:57 • Just your idea but this saves 2-3 key strokes:main(c){(c=getchar())>0&&main(),putchar(c);} – Quixotic Mar 9 '11 at 5:51 • Does C evaluate numbers as booleans? If so, c>=0 can become ~c – Cyoce Apr 4 '16 at 6:36 ### 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. • -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 Mar 6 '17 at 13:28
• @ConnorLSW: That doesn't even read from stdin. And $input is an enumerator yielding lines, so you can't stringize it like that. – Joey Mar 6 '17 at 13:31 ## Perl 5.1, 14 say~~reverse<> ## Befunge-93 - 11x2 (22 characters) >~:0v >:v ^ _$^,_@

Tested using this interpreter.

• Are you sure you didn't just press random keys on your keyboard? – Thomas O Feb 2 '11 at 21:57
• @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 Feb 2 '11 at 22:08
• 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. – Thomas O Feb 2 '11 at 22:11
• – clap Sep 14 '15 at 23:52

# Binary Lambda Calculus - 9 bytes

16 46 80 17 3E F0 B7 B0 40
• Know any good places to learn BLC? It looks like such a fun language! – phase Jul 14 '15 at 2:15
• @phase This looks useful if you can handle the amount of logic theory there: tromp.github.io/cl/LC.pdf – C0deH4cker Jul 26 '15 at 10:56

# Fission, 1614 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.

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

## ><>, 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.

i:0(7$. ~ol0=?;! • -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 Jan 16 '18 at 11:59 • @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 Jan 16 '18 at 16:22 • Hmm, actually this works just as well for 13 bytes (can't believe I missed the easy swap of 0=? to ?!) – Jo King Apr 20 '18 at 5:07 • @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 Aug 20 '19 at 12:03 • @TealPelican Yes, I mentioned that in my second comment – Jo King Aug 20 '19 at 14:33 # PHP - 38 17 characters <?=strrev(cat`); • What is cat?? – Xanderhall Nov 30 '16 at 17:56 • @Xanderhall probably reads from stdin – Pavel Nov 30 '16 at 18:48 ## 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. ## PHP, 82292429 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 • One problem: fgets(STDIN) only reads the first line. – PleaseStand Feb 1 '11 at 0:09 • Updated the code to now read all of the lines. – Kevin Brown Feb 5 '11 at 1:52 • Except you have an artificial limit of 1000 chars – anonymous coward Feb 5 '11 at 9:55 • Updated the limit to match the Python one below, I can't imagine anyone using that much though. – Kevin Brown Feb 6 '11 at 16:09 ## 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. • Here is a shorter version (10 chars): line 1: #v~ line 2::<,_@#. Funny that using j does not improve it here. – Justin Jan 10 '14 at 9:03 • @Quincunx that's clever, using the IP direction as a kind of implicit negation. – FireFly Jan 10 '14 at 10:47 # Pyth - 35 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 • Doesn't match the spec, unfortunately--the order of the lines needs to be reversed as well. – DLosc Jun 1 '15 at 1:23 • Fk_.z_k I'm sure someone can get something shorter than this, but that's what i got. – gcq Jun 1 '15 at 13:32 • @gcq I have a shorter version (5 chars), but I haven't gotten a chance to edit it. – kirbyfan64sos Jun 1 '15 at 17:07 • @DLosc Fixed! I just read all the input, joined via newlines, and reversed that. – kirbyfan64sos Jun 1 '15 at 22:49 • @FryAmTheEggman Ah, yes! Didn't know about that when I had posted this a few months back. – kirbyfan64sos Oct 23 '15 at 18:54 # 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. ## 05AB1E, 1 byte R R reverses the input. • 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. – Adnan Apr 26 '16 at 21:13 • @Adnan Thanks for the tip. – penalosa Apr 26 '16 at 21:36 ## 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. ## 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: 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. ## PHP - 44 characters <?=strrev(file_get_contents('php://stdin')); ## Perl print scalar reverse for reverse(<STDIN>); # 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.

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