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

94 Answers 94

3
\$\begingroup\$

Fuzzy Octo Guacamole, 2 bytes

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

^z

^ gets input, z reverses, and implicit output.

\$\endgroup\$
  • 1
    \$\begingroup\$ Can 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) \$\endgroup\$ – Downgoat Apr 4 '16 at 4:00
  • \$\begingroup\$ @Downgoat groans but decides to edit anyway \$\endgroup\$ – Rɪᴋᴇʀ Apr 4 '16 at 4:01
  • \$\begingroup\$ Linked to the github. \$\endgroup\$ – Rɪᴋᴇʀ Apr 4 '16 at 4:02
  • 1
    \$\begingroup\$ thanks. I'd upvote but I've already upvoted \$\endgroup\$ – Downgoat Apr 4 '16 at 4:02
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Link to this language? \$\endgroup\$ – MD XF Sep 19 '17 at 3:31
  • \$\begingroup\$ @MDXF You can download Game Maker 8.1 Lite or the free version of GM Studio if you want to try this out. \$\endgroup\$ – Timtech Sep 19 '17 at 11:57
2
\$\begingroup\$

Python - 35 chars

import os;print os.read(0,2e9)[::-1]
\$\endgroup\$
  • \$\begingroup\$ This is limited to 1e9 characters, though... not technically unlimited. \$\endgroup\$ – Thomas O Jan 30 '11 at 13:15
  • 2
    \$\begingroup\$ It's not even legal Python, it lacks an argument to os.read(). Should be os.read(0,...) \$\endgroup\$ – hallvabo Jan 30 '11 at 15:55
  • \$\begingroup\$ @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. \$\endgroup\$ – gnibbler Jan 30 '11 at 20:44
  • \$\begingroup\$ what about sys.maxint? \$\endgroup\$ – Thomas O Jan 30 '11 at 20:46
  • 1
    \$\begingroup\$ @gnibbler: import os,sys is possible. Even os.sys.maxint works for me (might be version/system dependent). \$\endgroup\$ – hallvabo Jan 30 '11 at 21:16
2
\$\begingroup\$

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;}
\$\endgroup\$
  • \$\begingroup\$ Can't you #define s string or something like that?or declare m and l at the same time? \$\endgroup\$ – Behrooz Oct 6 '13 at 20:05
2
\$\begingroup\$

Scala - 60

print(io.Source.fromInputStream(System.in).mkString.reverse)
\$\endgroup\$
2
\$\begingroup\$

Groovy 44 characters

args.reverse().each{print it.reverse()+" "}
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
<>
\$\endgroup\$
  • 3
    \$\begingroup\$ Just curious, why is -c counted as 3 bytes? \$\endgroup\$ – ETHproductions Jan 5 '17 at 23:35
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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). \$\endgroup\$ – Kevin Cruijssen Mar 3 '17 at 10:35
  • \$\begingroup\$ 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. \$\endgroup\$ – Jakob Aug 15 '17 at 0:46
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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 '=')

\$\endgroup\$
2
\$\begingroup\$

Brachylog, 1 bytes

(maybe noncompeting?)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Common Lisp, 67 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Japt, 1 byte

w

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

C# - 116

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

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

JavaScript - 44

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

alert(prompt().split('').reverse().join(''))
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save 7 bytes with some ES6: alert([...prompt()].reverse().join``) \$\endgroup\$ – andrewarchi Jun 15 '17 at 4:34
1
\$\begingroup\$

JavaScript - 50 48 47

Slightly longer than the other JS entry

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

><>, 17 bytes

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

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

\$\endgroup\$
1
\$\begingroup\$

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

Pyke, 1 byte (noncompetitive)

_

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Java, 103 bytes

Full programs in Java suck.

class A{public static void main(String args[]){System.out.print(new StringBuffer(args[0]).reverse());}}
\$\endgroup\$
  • 2
    \$\begingroup\$ Can't you change it from args to a? \$\endgroup\$ – FlipTack Dec 26 '16 at 14:20
  • \$\begingroup\$ FlipTack suggestion will save you 6 bytes, giving us a double digit Java solution. \$\endgroup\$ – NonlinearFruit Feb 20 '17 at 16:57
  • \$\begingroup\$ 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. \$\endgroup\$ – Jakob Aug 15 '17 at 0:49
1
\$\begingroup\$

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

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.

\$\endgroup\$

protected by Community Jul 15 '18 at 4:23

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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