Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program that prints its own source code out backwards.

Scoring:

  • +50 if you use pull data from the Internet.
  • +25 if you read your own source code.
  • +1 point per character
  • Lowest score wins.

Rules:

  • No using other files (e.g. reverse.txt)
  • Minimum code length is two characters.
  • Your program cannot be a palindrome.
share|improve this question
1  
Looks like this has been done before, just without the "no palindromes" rule. –  Iszi Dec 18 '13 at 18:59
2  
Are those scores bonuses or penalties? You need to specify in words if something is a penalty or a bonus, because saying +10 can be taken to mean either "score as if it had 10 more characters than it actually does" or "the code can have 10 more characters that won't be scored", or other interpretations. –  AJMansfield Dec 18 '13 at 20:24
6  
@AJMansfield Lowest score wins means that +x would be a penalty, -x would be a bonus. –  Iszi Dec 18 '13 at 20:32
4  
The one question I have, then, is why is pulling data from the internet given a larger penalty than reading the source file? –  AJMansfield Dec 18 '13 at 20:35
3  
Woohoo, 1st place on the hot network questions list :D Our site needs more attention... –  Doorknob 冰 Dec 19 '13 at 0:09

30 Answers 30

up vote 36 down vote accepted

GolfScript - 2


1

(ie \n1 where \n is the newline character)

Output:

1

(ie 1\n)


To quote Ilmari:

GolfScript automatically appends a newline to the end of the output

Thus a newline followed by a number will print the number followed by a newline.

share|improve this answer
5  
+1 I didn't think anything could beat the Mathematica solution. –  Kaya Dec 21 '13 at 19:55

huh?, 5 characters

!hcuO

I actually have NO idea how it works, but If you download the interpreter, and if you write !hcuO, then you get Ouch!

To run this, you need to execute the program like this:

huh.exe !hcuO

It will actually look for a file called !hcuO, but it doesn't exist, so it outputs Ouch!

share|improve this answer
60  
+1 for writing something you don't understand –  Cruncher Dec 18 '13 at 17:54
13  
Is it not just a little ironic that you don't understand how your own code works, in an esolang that by design isn't supposed to understand your code either? –  Iszi Dec 18 '13 at 18:08
    
@Iszi That's the joke. –  AJMansfield Dec 18 '13 at 20:17
5  
I'm not sure you're using huh? right, though I'm having a hard time finding proper documentation. It seems the usage is intended to be huh.exe <path to source code> and Ouch! is returned for an invalid path. Try putting your code into an actual file, and feeding that file as an argument to huh? and see what happens. It's also interesting to see that it generates a Notes.txt file with some commentary. –  Iszi Dec 18 '13 at 21:59
6  
Ok, this thing just told me it thinks it understands but I didn't see anything happen. Maybe I should stop toying with it on my primary system. –  Iszi Dec 18 '13 at 22:04

Mathematica, 3 chars

a 2

a 2 means a times 2. So the answer is 2 a.

share|improve this answer
1  
This will probably win unless someone can get a two char solution. –  ike Dec 20 '13 at 1:54
8  
In fact I know a two char solution. Also in Mathematica: 1#. The output is #1. –  alephalpha Dec 20 '13 at 11:24
2  
@alephalpha: Then you should post that as an answer! –  ProgramFOX Dec 20 '13 at 12:07
5  
@Ben The answer with the lowest score wins, as said in the question. –  Ramchandra Apte Dec 22 '13 at 3:33

H9+, 13 characters

!dlrow ,olleH

As the web page says, all characters that are not H, 9 or + are ignored, so my program will print Hello, world!

share|improve this answer
18  
The one and only practical benefit of crazy esoteric languages is to answer these crazy questions. –  totymedli Dec 19 '13 at 8:11
    
It'd be more practical if these questions were so. –  kojiro Dec 22 '13 at 18:50

Python, 27

xatnys dilavni :rorrExatnyS
share|improve this answer
17  
Doesn't this print a lot more than just "SyntaxError: invalid syntax", but also the file name and line? –  Lego Stormtroopr Dec 18 '13 at 23:26
3  
@Lego Stormtroopr: If ran from a file, yes. If typed or pasted directly in the interpreter, no. –  Emilio M Bumachar Dec 19 '13 at 13:34
2  
@EmilioMBumachar: This is the output in CPython 2.7.3 interactive interpreter... –  jazzpi Dec 19 '13 at 14:38
1  
@jazzpi: I get the same as you at the interpreter that Windows Commmand Prompt becomes after calling python.exe, but I get simply "SyntaxError: invalid syntax" at IDLE for python 3.3.2. I guess not all interpreters have the same behavior. –  Emilio M Bumachar Dec 19 '13 at 19:08

Javascript: 34 characters

reifitnedi detcepxenU :rorrExatnyS

outputs SyntaxError: Unexpected identifier, at least in the Chrome console

share|improve this answer
7  
Clever use of abusing the system through error abuse –  WallyWest Dec 19 '13 at 1:46
1  
You sir, have made my day :D –  major-mann Dec 19 '13 at 9:54
2  
Not an original idea, there already was an answer about this in python 2. –  Lohoris Dec 19 '13 at 13:53
1  
@Lohoris Sorry, I didn't see that one –  scrblnrd3 Dec 20 '13 at 14:58
1  
+1 bravo to you and thanks. –  DROP TABLE users Dec 20 '13 at 20:00

Python, 35 chars

This would be my sneaky attempt (assuming an empty directory), in bash commands. The code is written in Python:

$ mkdir ']1[)"."(ridtsil.so tnirp ;so tropmi'
$ echo 'import os; print os.listdir(".")[1]' > test.py
$ python test.py
]1[)"."(ridtsil.so tnirp ;so tropmi
$ cat test.py
import os; print os.listdir(".")[1]

Since files are forbidden, but not directories, this is allowed :P

share|improve this answer
18  
+1 For abusing the rules. –  Lego Stormtroopr Dec 18 '13 at 23:22
2  
Where is the reversal? Shouldn't the directory's name be: ]1[)"."(ridtsil.so tnirp ;so tropmi ? –  Kaya Dec 19 '13 at 1:08
    
@Kaya: Whoops yeah, fixed that. –  jazzpi Dec 19 '13 at 10:06
6  
Technically a directory is a file, though. –  Lohoris Dec 19 '13 at 13:52
7  
@Lohoris: Not in my totally awesome custom filesystem :P –  jazzpi Dec 19 '13 at 17:09

Python, 43 41

_=']0~::[_%%_ tnirp;%r=_';print _%_[::~0]
share|improve this answer

GolfScript, 12 chars

"-1%.`"-1%.`

This code takes the double-quoted string "-1%.`", reverses it (-1%), duplicates it (.) and un-evals (`) the second copy, restoring the double quotes around it.

Previous entry (13 chars):

{`'.~'+-1%}.~

Based on the 8-char quine {'.~'}.~ from this answer; the extra 5 chars are needed to stringify and reverse the output.

Ps. Note that GolfScript automatically appends a newline to the end of the output. If this is counted as part of the output, a corresponding newline can be prepended to either version of the code without affecting the output, for a cost of one extra char.

share|improve this answer

BASIC, 22 12 7 characters

:-)

1 enil ni rorre xatnyS

EDIT: If you're allowed to enter the program in immediate mode, then this could be reduced to rorre xatnyS (12 characters).

In BBC BASIC, you only need 7 characters:

ekatsiM
share|improve this answer

bash

$ dnuof ton dnammoc :found :hsab-
-bash: dnuof: command not found

Length: 31 characters.


sh

$ dnuof ton dnammoc :found :hs-
sh: dnuof: command not found

Length: 29 characters.

This one could not work on some Linux distributions, but works on OSX.


tcsh

$ .dnuof ton dnammoC :found.
.dnuof: Command not found.

Length: 26 characters.


csh

% .dnuof ton dnammoC :found.
.dnuof: Command not found.

Length: 26 characters.


The winner is:

ksh

$ dnuof ton :found :hsk
ksh: dnuof: not found

Length: 21 characters.


Above should work on all *unix based OS.

share|improve this answer
12  
Doesn't work for me, i have a command named dnuof –  Kroltan Dec 19 '13 at 14:23
5  
I forgot to add, it doesn't work on distributions which has dnuof installed (whatever it is). Damn hackers. –  kenorb Dec 19 '13 at 15:40
1  
Hahaha, there's a command named dnuof? :D what does it do? –  Doorknob 冰 Dec 19 '13 at 23:51

Perl, 41

$_=q{print~~reverse"\$_=q{$_};eval"};eval

Old 52 character answer (27+25 penalty)

open+0;print ~~ reverse <0>

Reads its own source, stores the reverse in a scalar, and prints that.

share|improve this answer
1  
The scalar operator can be replaced by ~~. However, you need to add +25 to your score for reading your own source code. –  breadbox Dec 18 '13 at 19:26
    
@breadbox noted –  smcg Dec 18 '13 at 19:39
    
+1. I was about to post something like my shell solution: $_='say"lave;\047",~~reverse,"\047=_\$"';eval, but your solution is shorter :-) Note that you can golf it down to 39 characters using say. Hope you will beat all the esoteric weirdness :-) –  Tomas Feb 1 at 20:26
    
@Tomas are you suggesting replacing print with say? That ends up not printing anything. –  smcg Feb 3 at 14:58
    
Did you run perl with -Mfeature=say option? –  Tomas Feb 3 at 15:19

J: 26

Standard quining (26 chars): by defining a function and passing it its own definition, in quotes:

|.(,],2#{:)'|.(,],2#{:)'''

Could probably be made shorter.

J-specific (33 chars): by defining a variable and asking what file the variable was defined in, i.e. this one, then printing out the contents of that file:

1!:2&2|.1!:1(4!:4 a=:<'a'){4!:3''

Must be saved & run from a script (i.e. not in the REPL, because then the answer to the question is "your argument wasn't defined in a file", so there's no file to read).

share|improve this answer
    
The second one should get the + 25 bonus to read the own file. –  Johannes Kuhn Dec 18 '13 at 20:04
1  
@JohannesKuhn: Penalty, but yeah. –  jazzpi Dec 19 '13 at 10:08
1  
"Bonus" sounds nicer. –  Johannes Kuhn Dec 19 '13 at 10:15

TI-BASIC, 2

i2

Where i is the imaginary number.

Outputs 2i

share|improve this answer
1  
This only works in the home screen, not inside a PRGM. –  kernigh Jun 28 at 3:27

Ruby, 60

puts(2,s=<<2.chop.reverse,s)
puts(2,s=<<2.chop.reverse,s)
2

Based on a classic Ruby quine.

share|improve this answer
    
Nice use of heredocs. –  Jon Purdy Dec 23 '13 at 19:25

Befunge 98 - 10 chars

"8k,'!1+,@

This works if your interpreter does not interpret wrapped lines after " as adding an extra space. If your interpreter does interpret wrapped lines like that, then this 11 char solution works (because duplicate spaces in a string literal are interpreted as one):

"9k,'!1+,@ 

If I can use g without penalty, then these also work (7 and 8 chars respectively):

"5k,g,@

and

"6k,g,@ 
share|improve this answer

C++ 472 characters

A lot of characters but I cant think of a simpler way in a c-based language.

#include<iostream>
#include<string.h>
#define p(t) std::cout<<'}'<<';'<<')'<<strrev(&std::string(#t)[0])<<t;
char* strrev(char*p){char*t=p;char*q=p;while(q&&*q)++q;for(--q;p<q;++p,--q)*p=*p^*q,*q=*p^*q,*p=*p^*q;return t;}
int main(){p("(p{)(niam tni};t nruter;q*^p*=p*,q*^p*=q*,q*^p*=p*)q--,p++;q<p;q--(rof;q++)q*&&q(elihw;p=q*rahc;p=t*rahc{)p*rahc(verrts *rahc;t<<)]0[)t#(gnirts::dts&(verrts<<')'<<';'<<'}'<<tuoc::dts )t(p enifed#>h.gnirts<edulcni#>maertsoi<edulcni#");}
share|improve this answer
1  
+1 for top level simplicity –  Shingetsu Dec 28 '13 at 5:28

PHP, 41 characters (+25)

Don't know if I understood the assignment correctly. But here's a PHP try:

while(!isset($s) || $s) echo isset($s) ? array_pop($s) : ($s = str_split(file_get_contents(__FILE__)) and null);

edit: this can be much shorter:

echo strrev(file_get_contents(__FILE__));

But since it can be that simple, this is probably not what is being asked...

share|improve this answer
    
phpFiddle: phpfiddle.org/main/code/fuy-mv0 –  nl-x Dec 18 '13 at 20:24
    
When I click run, I get a whole bunch of useless nonsense (here is a short snippet of it: >? ;)llun dna ))__ELIF__(f$(tilps_rts = s$( : )s$(pop_yarra ? )s$(tessi ohce )s$ || )s$(tessi!(elihw ;"stnetnoc_"=.f$ ;'teg_elif'=f$ php?<>?}};ESLAF nruter;"ec6x\i66x\02x\e47x\96x\rw ; there is much much more). Also, include your character count; this is a code golf. Also, it seems that you are reading your source file, so add 25 to your character count and that is your score. Lowest score wins. –  Quincunx Dec 18 '13 at 21:30
    
@Quincunx First off, it is backwards ... but secondly, this is the source code that phpfiddle generates! (but backwards...) They seem to escape a lot of thing, trying to keep things safe. Replace array_pop with array_shift to see the source code not backwards... –  nl-x Dec 18 '13 at 21:33
    
Yes I can see the reversed source code, but what is with all the extraneous text? There are a lot of escape sequences, but there are some that aren't (eg: ESLAF nruter ie return FALSE). –  Quincunx Dec 18 '13 at 21:36
    
@Quincunx Sorry, I'm not catching if you are showing interest in the way phpFiddle works, or if you are criticizing my code. If it's the latter, then in my defense, put my code in a .php file and run it in a browser, and it'll work cleanly. I just thought phpfiddle was a nice thing to let you see, so you can see a bit of it's inner workings. –  nl-x Dec 18 '13 at 21:42

MATLAB, 78 characters:

 
|
.snoisserpxe ro stnemetats BALTAM ni dilav ton si retcarahc tupni ehT :rorrE

Note that the solution requires you to begin with a special character (alt+0160) and that it prints exactly the reversed message. (Unlike the python solution)

share|improve this answer

JavaScript jQuery 119 92 74 70 characters

alert($("#answer-16051 pre code").text().split("").reverse().join(""))

Now using jQuery, as minitech suggested in the comments, and manually wrapping with <pre><code> so I can use text() without fear of other code blocks in this post interfering. Manually wrapping with <h4> was incompatible with chromeium when I tested it, so now it should work in most browsers.

This program, if run from this page, finds the code block directly above, reverses its contents, and puts it in an alertbox.

Its easy enough to verify, just paste it into the dev console.

share|improve this answer
    
This is way longer than just using a function. And you should use jQuery (on this page) or at least querySelector anyways… –  U2744 SNOWFLAKE Dec 19 '13 at 17:58
    
@minitech thanks for the tip, I swapped it for a querySelector now. I would like to look into the jQuery possibility, but it looks like it will take a little longer for me to figure out. –  AJMansfield Dec 19 '13 at 18:37
    
@minitech ok, thanks for the jQuery tip. (I only started learning javascript yesterday.) –  AJMansfield Dec 19 '13 at 18:45

UNIX shell, 31

Real solution at 52 characters:

A='printf "A$ lave;\047`echo $A|rev`\047=A"';eval $A

But beware! Honesty doesn't pay off in today's world! Penalty is too low!!

6 chars + 25 = 31:

rev $0
share|improve this answer
    
On OSX rev $0 generates the error: rev: illegal option -- b. –  kenorb Jul 21 at 13:21

JavaScript, 62

function f(){alert((f+'f()').split('').reverse().join(''))}f()

Works for me on latest Chrome (v 31.0.1650.63). Some other browsers may give a different output. (If you reverse that output, then it would work :P)

share|improve this answer

Piet, 2 characters

(or 0, depending on the definition of "character")

Source code:
enter image description here

Output:
enter image description here

Look carefully, it is there. Try selecting/highlighting the image.

share|improve this answer
5  
Can you increase the codel size so that the image is visible? Also, why are the two images identical? Wouldn't that make it a palindrome? –  Quincunx Dec 19 '13 at 4:21
7  
Please describe the input so it can be reproduced. As is it seems to be a palindrome but its hard to tell. –  Dennis Jaheruddin Dec 19 '13 at 12:03
    
@Quincunx Hmm... I guess you're right about the palindrome part. :\ –  The Guy with The Elf Hat Dec 19 '13 at 17:16
1  
Your source code and output iamges refer to the same file –  Eric Dec 19 '13 at 17:48
    
@Eric Yes. I see no reason to upload two identical files. –  The Guy with The Elf Hat Dec 19 '13 at 20:57

JavaScript, 56

($=_=>_!=$._?_?$(_.slice(1))+_[0]:')':$('($='+$+')('))()
share|improve this answer
    
Please state your environment because this does not work in Chrome. Is this Rhino or what? –  George Reith Dec 20 '13 at 13:39
    
@GeorgeReith: Anything with ES6 arrow function support. All SpiderMonkeys should work fine, for example (Rhino included). –  U2744 SNOWFLAKE Dec 20 '13 at 14:42

Perl, 49 characters

(Note: the actual program is three lines long, the third line being empty.)

print$/,~~reverse<<''x2
print$/,~~reverse<<''x2
 

Newlines can be a little unintuitive when text is reversed: the output starts with two blank lines. A naive user might expect the output to look more like this program, which is actually significantly shorter:

say~~reverse<< x2
say~~reverse<< x2
 

But only first listing is actually correct.

share|improve this answer

Racket 178

(let((l(list->string(reverse(string->list"(let((l(list->string(reverse(string->lista~a~a~))))(q (integer->char 34)))(printf l q l q))"))))(q (integer->char 34)))(printf l q l q))

Output:

))q l q l ftnirp()))43 rahc>-regetni( q())))"))q l q l ftnirp()))43 rahc>-regetni( q())))~a~a~atsil>-gnirts(esrever(gnirts>-tsil(l((tel("tsil>-gnirts(esrever(gnirts>-tsil(l((tel(

Using the powerful printf makes it almost cheating (though I see people pulling their own sources for only 25 penalty.)

share|improve this answer

Lua, 31 Characters

'''' raen rorre xatnys :1:tupni
share|improve this answer
    
Looks like lua to me, on LUA it says STDIN:1: syntax error near 'rorre' –  mniip Jan 31 at 4:52

C, 148

char *a="};)43,b,43,a(ftnirp;]i-57[a=]i[b)++i;67<i;(rof{)(niam;i,]99[b,%c%s%c=a* rahc",b[99],i;main(){for(;i<76;i++)b[i]=a[75-i];printf(a,34,b,34);}

Just a fun play on a typical C quine.

share|improve this answer

Ruby, 33+25=58

print File.read(__FILE__).reverse
share|improve this answer

PHP, 59

34 + 25 for reading own sourcecode.

<?=strrev(join(file((__FILE__))));

Online demo

share|improve this answer
1  
Doesn't this get the 25 penalty? –  ike Dec 19 '13 at 15:25
    
@ike you're right, I edited accordingly –  HamZa Dec 19 '13 at 20:58

protected by Community Dec 23 '13 at 6:30

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

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.