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
    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
    Feb 2, 2011 at 18:33
  • 1
    \$\begingroup\$ @Joey Adams, yep, it should replicate the input exactly. \$\endgroup\$
    – Thomas O
    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
    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\$ Aug 18, 2020 at 5:10

140 Answers 140

1 2 3 4
5
0
\$\begingroup\$

Java (JDK), 96 bytes

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

Try it online!

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

Zsh (builtins only), 22 bytes

<<<${(j::)${(Oas::)*}}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ TODO: fix so it actually reads from STDIN :P \$\endgroup\$
    – roblogic
    Dec 11, 2020 at 3:26
0
\$\begingroup\$

BRASCA, 1 bytes

Another simple 1-byter.

,

Explanation

<implicit input>    - Push STDIN to the stack
,                   - Reverse the stack 
<implicit output>   - Output the stack, reversed.

Language Link

Github Repo

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

Burlesque, 3 bytes

<-Q

Try it online!

Explanation:

      # Implicit input
<-    # Reverse
  Q   # Pretty format (removes wrapping "")
      # Output stack
\$\endgroup\$
0
\$\begingroup\$

Whispers v2, 79 bytes

> InputAll
> 0
>> #1
>> (3]
>> 2-L
>> Each 5 4
>> 1ⁿL
>> Each 7 6
>> Output 8

Try it online!

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

Twue, 31 bytes

@!#␀::=
@!::>@!#.
#_::~_
::=
@!

Try it on the website! (Note, ␀ represents the byte 0x00, here in the snippet and in the rest of the explanation.)

This was a bit trickier than it might first seem, since we need to account for the fact that the input may contain any character, and hence, may bungle any particular replacement. To combat this, we use the two-character @! which is constantly replaced with @!#., where . is a byte of input, until EOF is hit, eventually looking something like this:

@!#␀#g#o#d# #y#z#a#l# #e#h#t# #r#e#v#o# #d#e#p#m#u#j# #e#H#
#x#o#f# #n#w#o#r#b# #k#c#i#u#Q

Our termination condition is @!#␀. Now, if we were to just use a single character, say @, to take input, the program would then continue to perform replacements on any such character in the input. By separating each character by #, we ensure that @! can never appear as a substring given any input.

The rest of the program is simple; #_ outputs each character, removing the # and that character, until no more replacements can be made. This will work even for # characters present in the input, as the first #_ in the string is matched every time, and we do not start processing these until the input is fully read.

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

Duocentehexaquinquagesimal, 4 bytes

;&Oo

Try it online!

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

itflabtijtslwi, 233 204 bytes

/Z/\/\///Y/\\\\ZH/Y>ZF/P.ZE/C.ZD/.BZB/\/.ZA/Y.Y./B/<Y\HYYYZP1/GGE2GG./E1E3D\./F2.\D\DB/E1D\./F2.\./p.2.AAB/E3D\D/E1E2E3./F1./F3D/p.\2./F1D/<.HDB/F\3./F1D/<.H./<.A\.H.AAA/F2ZP\2/P1Z<HZ/P\3/P1Z<H/<Y\HYYY/P2

Try it online!

Original

I am not familiar with the language well; I barely understand how the program works. This is a modification of cat program.

/./<\\\\>\\\\\\//P1/GGC.2GG./C.1C.3./.\./P.2.\./.\./././C.1./.\./P.2.\./p.2.\.\.\.\././C.3./.\././C.1C.2C.3./P.1./P.3././p.\2./P.1././<.\>./././P.\3./P.1././<.\>./<.\.\.\.\>.\.\.\.\.\.\./P.2//P\2/P1//<\>///P\3/P1//<\>/<\\\\>\\\\\\/P2

Try it online!

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

Pxem, Filename: 15 bytes + Content: 0 bytes = 15 bytes.

  • Filename (escaped): .w.i.c\001.+.a.s.p
  • Content: empty

Try it online!

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

Branch, 10 bytes

,[/,]^[.^]

Try it on the online Branch interpreter!

This works pretty much the same was as the BF answer does. Actually my language is proven TC by being a direct superset of BF, because if you only use the left branch, then you can use / and ^ in place of > and <, and { and } in place of - and + to translate any BF program into Branch (though you will have to do a bit of manipulation with the right branch if you want to depend on BF cells wrapping at 256).

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

Swift, 86 bytes

var o=""
while let s=readLine(){o="\n" + .init(s.reversed())+o}
print(o,terminator:"")

As far as I'm aware, Swift doesn't have any builtin facilities to get stdin as a sequence that I can just call reversed() on. There's something in the Foundation library that I could for try await over, but the extra setup makes it not worth it.

Try it online!

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

K (ngn/k), 2 bytes

|:

Try it online!

Trivial questions got trivial answers. If it wasn't for the Right operator (:) this could be a one-byter though.

K (ngn/k), 5 bytes

`0:|:

Try it online!

This one outputs back to stdout, which is what the challenge specifies.

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

Z80Golf, 12 bytes

00000000: cd03 8038 03f5 e9ff f130 fc76            ...8.....0.v

Try it online!

start:
    ; while (A = getchar() != EOF)
    ;     push A
.read:
    call   0x8003         ; CD 03 80 -> call getchar
    jr     c, .next       ; 38 03    -> jump to .next if carry (EOF)
    push   af             ; F5       -> Push input to stack
    jp     (hl)           ; E9       -> Jump to HL which == 0 (jr .read)
    ; while (A = pop() != EOF)
    ;     putchar(A)
.write:
    rst    0x38           ; FF       -> Print A
.next:
    pop    af             ; F1       -> Pop input to print
    jr     nc, .write     ; 30 FC    -> print and loop if no carry
    halt                  ; 76       -> Exit

The loops do have a bit of a tricky structure because of how the entry points are and how I am cheeky with jp (hl) instead of jr .read since hl == 0x0000. For all intents and purposes, these are two C style while loops.

Detecting when there is EOF in z80golf is easy, as the getchar syscall will set the carry flag. When the carry is not set, I push the input to the stack and loop again.

However, as for detecting when the input starts, that is a whole new problem. And to answer that, we first need to talk about parallel universes. Or rather...flags.

push af and pop af also push and pop the FLAGS register. It has the following structure

|  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
|  S  |  Z  | n/a |  H  | n/a | P/V |  N  |  C  |

Initially, the FLAGS are 00000000, so the stack looks like this if I type "foo":

      A  F    FLAGS
FFFA: 6F 00 (--------)
FFFC: 6F 00 (--------)
FFFE: 66 00 (--------)

However, when the stack is empty, it wraps around to 0x0000 which is where the code is, and notably, call 0x8003 will set the C flag, which I can test with a jr nc.

      A  F    FLAGS
0000: CD 03 (-----PNC)
0002: 80 38 (---H----)
...
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 3 bytes

-1%

Try it online!

Unless you can somehow represent -1 in one byte, I'm fairly certain 3 bytes is the lowest possible score here.

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

Go, 103 bytes

import(o "os";."io";."fmt")
func f(){s,_:=ReadAll(o.Stdin)
for i:=len(s)-1;i>=0;i--{Printf("%c",s[i])}}

Attempt This Online!

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

Python, 20 Bytes

print(input()[::-1])

[::-1] is the actual thing that reverses the string. Since I haven’t looked at all the answers and this is a trivial programme, I highly suspect this is a duplicate.

\$\endgroup\$
1
  • \$\begingroup\$ This doesn't work if there are newlines in the input. There are two similar answers that have already been deleted \$\endgroup\$
    – Jo King
    Jun 18 at 23:35
0
\$\begingroup\$

Lua, 31 bytes

io.write(io.read"*a":reverse())

Try it online!

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

StackCell, 11 bytes

1[@:]`:[;:]

Assumes input does not contain any null bytes, as they would be treated as EOF

Explanation:

  • 1: Skip the next instruction ([)
  • ([): The start of a loop. Never executed
  • @: Input a character from stdin
  • :]: Duplicate the top value of the stack, and if it is non-zero jump back to the matching [, else continue
  • `: Discard the top value of the stack (0)
  • :[: Duplicate the top value of the stack, and if it is zero jump to after the matching ], else continue
  • ;: Print the top value of the stack, as a character
  • :]: Duplicate the top value of the stack, and if it is non-zero jump back to the matching [, else continue (and halt the program)
\$\endgroup\$
0
\$\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\$

Lua, 27 bytes

print(io.read'a':reverse())

This is Lua 5.4 and 5.3 compatible. If you want Lua 5.2, 5.1 and LuaJIT compatible then you need one more byte:

print(io.read'*a':reverse())
\$\endgroup\$
1 2 3 4
5

Your Answer

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

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