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

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>

• 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

## 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  # 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. # 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: Actual bytes can be saved by using more typing - this takes up less room in the ZX81 RAM but is longer: 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.

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

• 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 Apr 12 '17 at 8:18
• @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 Apr 12 '17 at 8:40
• @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 Apr 12 '17 at 8:45

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

# Aceto, 3 bytes

r~p

r reads input
~ reverses it
p prints it


Try it online!

# Julia 0.6, 33 bytes

print(reverse(readstring(STDIN)))


Try it online!

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

• Um – MD XF Feb 19 '18 at 0:45
• @MDXF That has a trailing newline. – Conor O'Brien Feb 19 '18 at 0:49
• I don't see in the challenge spec that that isn't allowed; it typically is with outputting. – MD XF Feb 19 '18 at 0:50
• @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 Feb 19 '18 at 0:50

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


# 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! # 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. • 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 Oct 27 '19 at 11:50 • 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 Oct 27 '19 at 12:02 • I'll do that, thank you! – Hello Goodbye Oct 27 '19 at 12:58 # 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). # 1+ (EOF returns 0), 17 bytes 1##,"1<1+#+(|;())  Try it online! The TIO link uses integer I/O and a so-called input template (I'm going to use it for all my 1+ answers from now on) because 1. The interpreter reads input and source code from the same place for some reason and 2. It does not support EOF so I have to simulate it by manually putting the EOF in the input and 3. The NUL character cannot be placed in the input so I have to use integers. ## Explanation This supports all printable ASCII (and LF and CR), and the question didn't say anything about other unprintable characters so I guess that is okay. The first part of the program, 1##,"1<1+#+, reads the input to the stack. Here we save 2 bytes by comparing n <= 1 (1<) and not n <= 0 (which is 1+1<) since in 1+, 1 is the only literal, which indicates pushing a 0 is longer. After the loop, we have the input and a trailing EOF (0) on the stack. We get rid of the EOF by adding the top two numbers (this doesn't work for empty input, but again, the question didn't say anything about it!) and since a + 0 = a it will not affect the rest of the input. The second part, (|;()), is a simple recursive function that (pop and) outputs top of stack and it terminates with error when there are no more elements to output. I used recursion because loop is longer. ## Supports all ASCII characters except NUL, 19 bytes 1##,"1+1<1+#+(|;())  # Flurry, 52 bytes []{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}[<>()][(){()}]{}  ### Run example $ printf "Quick brown fox\nHe jumped over the lazy dog" | ./flurry -bnb -c \
"[]{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}[<>()][(){()}]{}"
god yzal eht revo depmuj eH
xof nworb kciuQ


Being a stack based language with stack content I/O, the task is essentially to reverse the entire stack. But due to how Flurry is designed, I had no choice but construct an encoding of a list containing all the stack contents, and then fold through the list to push the content one by one, in reverse order.

I decided to use the Church right-fold encoding and its variations: (in all cases, the bottom of the stack appears as the head of the list)

• Regular right fold
-- right fold; (1:2:3:4:nil) f n = f 1 (f 2 (f 3 (f 4 n)))
nil = \cn. n = SK
cons = \htcn. ch(tcn)
= \htc.S(K(ch))(tc)
= \ht.S(\c. S(K(ch))) t
= \h. S(\c. S(K(ch)))
= \h. S(\c.<SK>(ch))
= \h. S(S(K<SK>)(SI(Kh)))
= <S(S(K<SK>))(SI)K>
= <S(<SK><SK>)(SI)K>
= <<>[(<<>()>){}][<>{{}}]()>
listify = height (\t. S cons (K t) pop) nil
= []{<><<>[(<<>()>){}][<>{{}}]()>[(){}]{}}[<>()]

• Right fold, but with flipped args
-- right fold with flipped args; (1:2:3:4:nil) f n = f (f (f (f n 4) 3) 2) 1
cons' = \htcn. c(tcn)h
= \htc. S (\n. c(tcn)) (Kh)
= \htc. S (S(Kc)(tc)) (Kh)
= \ht. S (\c. S (S(Kc)(tc))) (K(Kh))
= \ht. S (S(KS)(\c. S(Kc)(tc))) (<KK>h)
= \ht. S (S(KS)(\c. <SK>c(tc))) (<KK>h)
= \ht. S (S(KS)(S<SK>t)) (<KK>h)
= \ht. S(<SK>S(S<SK>t)) (<KK>h)
= {{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}}
listify
= []{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}[<>()]

• Left fold
-- left fold; (1:2:3:4:nil) f n = f (f (f (f n 1) 2) 3) 4
cons = \htcn. t c (c n h)
= \htc. S (K (tc)) (\n. cnh)
= \htc. S (K (tc)) (S c (K h))
= \ht. S <SKt> (S S (K (K h)))
= {{<><<>(){}>[<[<><>]()()>{}]}}
listify = height {cons (t=arg; h=pop)} nil
= []{<><<>(){}>[<[<><>]()()>{}]}[<>()]


Out of the three, only right folds are feasible for stack reversal because the 4 must be handled (i.e. pushed to the stack) first. Then, the strict evaluation of Flurry makes the "flipped args" version easier to use for the task, because partial evaluation such as f 1 part of f 1 (f 2 (...)) may trigger the unwanted side effect to the stack.

So far, we got the function that transforms the stack into a fold function, which looks like \fn. f (f (f (f n 4) 3) 2) 1. Now is the time to decide what f (binary function) and n (starting value) should be.

f should basically ignore the first argument and push the second argument. Return value is irrelevant. So we can simply do this:

f = \xy. push y
= K (\y. push y)
= (){({})}


But {...} already implicitly pushes its argument, so we can just use a dummy result that is ignored every step:

f = (){()}


n can be anything too, so we use a dummy 2-byte token {}.

The full program is:

main = listify_stack_foldr_flip f n


# 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

• @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 Sep 29 '15 at 2:11

# Hassium, 62 Bytes

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


Run and see expanded here

# Javascript (ES6), 37

Really simple. Try below in Firefox.

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

# 𝔼𝕊𝕄𝕚𝕟, 4 chars / 8 bytes (noncompetitive)

ôᴙï)


Try it here (Firefox only).

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

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

Compressed:

.$@.>;<..\'"/$\$/}{,<..>.../  Try it Online! • 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 Aug 13 '16 at 20:09 # 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.  # tcl, 30 puts [string rev [read stdin]]  To terminate input press Ctrl+D. Available to run on: https://goo.gl/18Sqz0 # Python 2, 39 bytes import sys;print sys.stdin.read()[::-1]  • import sys;print sys.stdin.read()[::-1] is shorter. – user45941 Apr 4 '16 at 5:37 # 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. • If this is remarkably unclear, ping me and I'll fix it tomorrow. I'm tired. :P – MD XF Jun 15 '17 at 4:25 # Braingolf, 4 bytes &,&@  Try it online! Possibly non-competing? Another reverse builtin # 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  # 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).  # 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  # Jelly, 6 bytes ⁸ƈ;$ÐL


Try it online!

## Matlab (56)

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


## Execution:

abc
def

b =

fed
cba

• I believe [flip(a),10,b] should work? – Stewie Griffin Nov 2 '17 at 13:19
• @StewieGriffin Yes seemingly. – Abr001am Nov 2 '17 at 16:41