67
\$\begingroup\$

Requirements:

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

Example:

Input:

Quick brown fox
He jumped over the lazy dog

Output:

god yzal eht revo depmuj eH
xof nworb kciuQ

Shortest wins.

Leaderboard:

var QUESTION_ID=242,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

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

140 Answers 140

1
\$\begingroup\$

Knight (v2.0-alpha), 37 bytes

;=s=t@;W=gP=s+s+g"
";Ws;=t+[s t=s]sOt

Try it online!

Nothing super exciting, except for the fact that we can use @ instead of "" for the initial value of s and t.

\$\endgroup\$
4
  • \$\begingroup\$ why do you have an extra trailing newline in the code? \$\endgroup\$
    – naffetS
    Commented Sep 18, 2022 at 13:48
  • \$\begingroup\$ There's no way to know whether the input ended with or without a newline in Knight, as PROMPT strips them. So I decided to just pick the easier route. If you wanted to exclude the trailing newline, it'd just be O]t \$\endgroup\$
    – Sampersand
    Commented Sep 18, 2022 at 21:24
  • \$\begingroup\$ Trailing newlines in the code have nothing to do with the input. \$\endgroup\$
    – naffetS
    Commented Sep 18, 2022 at 22:51
  • \$\begingroup\$ Oh I see what you mean! Whoops, I'll edit that away \$\endgroup\$
    – Sampersand
    Commented Sep 18, 2022 at 23:11
1
\$\begingroup\$

Vyxal, 1 byte

Try it Online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Does this actually reverse multiline input from STDIN, as per the title & description? I don't have it running locally, but the tutorial suggests that implicit input from STDIN is read one line at a time... \$\endgroup\$ Commented Nov 16, 2022 at 13:59
  • \$\begingroup\$ @DominicvanEssen multiline input is given like "abc\ndef\nghi" \$\endgroup\$
    – lyxal
    Commented Mar 3, 2023 at 7:23
  • \$\begingroup\$ Wouldn't that more be a single-line string with escape characters representing newlines, rather than input containing actual newline characters? If you pipe it using echo -e "abc\ndef" (not echo "abc\ndef") does it work? \$\endgroup\$ Commented Mar 3, 2023 at 8:10
1
\$\begingroup\$

Thunno W, 1 byte

(actually \$ 1 \log_{256}(96) \approx \$ 0.82 bytes, but that doesn't show up on the leaderboard)

r

Attempt This Online!

Also works in Thunno 2: Attempt This Online!

   # Implicit input.
   # The W flag reads the whole of STDIN as a multi-line string,
   # rather than taking each line separately.
r  # Reverse the string on the top of the stack.
   # Implicit output.
\$\endgroup\$
1
\$\begingroup\$

ForWhile, 24 22 19 16 14 bytes

Saved 2 bytes due to new language feature of looping without pushing loop counter ([…) instead of (…))

9:`['1+_:~).[#)

Try it at the online interpreter!

This took me so long to figure out!! But I made it there in the end. I don't think the program can get shorter than this (but you never know…)

Thanks bsoelch for the tip to get large numbers.

Explanation:

9:`  \ 9 ^ 9
[    \ repeat (9 ^ 9) times:
  '  \   swap two items on the stack
  1+ \   add one (to string length)
  _  \   read a byte from STDIN
  :~ \   duplicate, bit flip; -1 (EOF) becomes 0
)    \ pop top of stack; if nonzero (not EOF) jump back to [
.    \ pop final -1
[    \ repeat (string length) times:
  #  \   print byte without popping
)    \ pop top of stack; if nonzero, jump back to [

ForWhile, 70 bytes

This one works for input of infinite size; ForWhile doesn't really support infinite loops, but you can do source-modification to make it work. Thanks bsoelch for writing this one.

""(,#)6~$~7~$(!;$1-:){}9+:57(.:@;57-$1-:).7~@_:~![..7~@34;$?];$1+7~$57

Try it at the online interpreter!


For the record: for ForWhile, reversing the string is the easy part of this challenge. The hard part is reading all of STDIN as a string. If the string could be passed as an argument to a procedure, this could be 5 bytes:

{[#)}

Try it at the online interpreter!

\$\endgroup\$
7
  • \$\begingroup\$ It is nice to see someone else try out my language. Your first solution depends on a bug in the interpreter (the source code should have been interpreted as UTF-8) that has now been fixed. The intended way is get large numbers is the ` operator (integer powers) e.g. 9:` will give you 387420489 using just 3 bytes. I could get you solution down to 19 bytes (~9:`(.1+_';~)'.(.#)) \$\endgroup\$
    – bsoelch
    Commented Jul 17, 2023 at 20:28
  • \$\begingroup\$ @bsoelch Thank you for the tip! (This is Jacob who opened those issues on GitHub.) \$\endgroup\$ Commented Jul 17, 2023 at 20:31
  • \$\begingroup\$ @bsoelch What does that semicolon do? I don't see anything about it in the docs. \$\endgroup\$ Commented Jul 17, 2023 at 20:33
  • 1
    \$\begingroup\$ ; is the "over" stack operator (copies the value below the top element above the top value) \$\endgroup\$
    – bsoelch
    Commented Jul 17, 2023 at 20:44
  • 1
    \$\begingroup\$ I found a solution for "infinite" input length ""(,#)6~$~7~$(!;$1-:){}9+:57(.:@;57-$1-:).7~@_:~![..7~@34;$?];$1+7~$57 (70 bytes) \$\endgroup\$
    – bsoelch
    Commented Jul 17, 2023 at 21:44
1
\$\begingroup\$

05AB1E, 3 1 byte

R

Try it online! Takes input surrounded in """triple double quotes""".

R  # full program
R  # reverse...
   # implicit input
   # implicit output
\$\endgroup\$
1
\$\begingroup\$

(,) 124 110 72 51 Chars or \$51\log_{256}(3)\approx\$ 10.1 Bytes

(,((()),(()(),(()())((())))),,((())),((()),(()))())

Into the explanation:
The code works by backindexing. Basically setting input to a negative number will next give that many characters from the back. It uses that to make input next give -1 by setting input to 0 (in the loop condition). Then, it sets input to (setting variable 2 to variable 2 + input). Then, it outputs input

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

Hassium, 62 Bytes

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

Run and see expanded here

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

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

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

Hexagony, 28 bytes (Non-competitive)

Compressed:

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

Try it Online!

\$\endgroup\$
1
  • \$\begingroup\$ 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). \$\endgroup\$ Commented Aug 13, 2016 at 20:09
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

tcl, 30

puts [string rev [read stdin]]

To terminate input press Ctrl+D.

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

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

Python 2, 39 bytes

import sys;print sys.stdin.read()[::-1]
\$\endgroup\$
1
  • 1
    \$\begingroup\$ import sys;print sys.stdin.read()[::-1] is shorter. \$\endgroup\$
    – user45941
    Commented Apr 4, 2016 at 5:37
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ If this is remarkably unclear, ping me and I'll fix it tomorrow. I'm tired. :P \$\endgroup\$
    – MD XF
    Commented Jun 15, 2017 at 4:25
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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).
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Jelly, 6 bytes

⁸ƈ;$ÐL

Try it online!

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

Matlab (56)

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

Execution:

abc
def


b =


fed
cba
\$\endgroup\$
2
  • \$\begingroup\$ I believe [flip(a),10,b] should work? \$\endgroup\$ Commented Nov 2, 2017 at 13:19
  • \$\begingroup\$ @StewieGriffin Yes seemingly. \$\endgroup\$
    – Abr001am
    Commented Nov 2, 2017 at 16:41
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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

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

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.

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

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
\$\endgroup\$
0
\$\begingroup\$

Ahead,  9  13 bytes

~ilj~#
 >dko@

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

Try it online!

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

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!

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

Brain-Flak, 12 bytes

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

Not going to be winning with this, but it works

Try it Online!

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

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.

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

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
\$\endgroup\$
0
\$\begingroup\$

Elixir, 42 bytes

IO.puts String.reverse IO.read :stdio,:all
\$\endgroup\$
0
\$\begingroup\$

MAWP, 16 bytes

[25W|]%%~%%0~[;]

Try it!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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