share
Stack OverflowProgramming challenge: can you code a hello world program as a Palindrome?
[+126] [69] Assaf Lavie
[2009-03-18 19:28:01]
[ language-agnostic puzzle palindrome ]
[ http://stackoverflow.com/questions/659752/programming-challenge-can-you-code-a-hello-world-program-as-a-palindrome ] [DELETED]

So the puzzle is to write a hello world program [1] in your language of choice, where the program's source file as a string has to be a palindrome [2].

To be clear, the output has to be exactly "Hello, World".


Edit:

Well, with comments it seems trivial (not that I thought of it myself of course [sigh].. hat tip to cobbal [3]).

So new rule: no comments.


Edit:

I feel kind of bad editing someone else's question to say this, but it will eliminate a lot of non-palindromes that keep popping up, and I'm tired of seeing the same simple mistake over and over.

The following is NOT a palindrome:

()()

The following IS a palindrome:

())(

Brackets, parenthesis, and anything else that must match are a major barrier to palindrome-ing, yes, but that doesn't mean you can ignore them and post non-palindrome answers.


Languages represented thus far:

C, C++, Bash, elisp, C#, Perl, sh, Windows shell, Java, Common Lisp, Awk, Ruby, Brainfuck, Funge, Python, Machine Language, HQ9+, Assembly, TCL, J, php, Haskell, io, TeX, APL, Javascript, mIRC Script, Basic, Orc, Fortran, Unlambda, Pseudo-code, Befunge, CFML, Lua, INTERCAL, VBScript, HTML, sed, PostScript, GolfScript, REBOL, SQL

(1) I am confused a little. How can the output be "Hello, World" when that is not a palindrome? - Ascalonian
It's not the output that needs to be a palindrome, it's the program itself. - Assaf Lavie
Gotcha. Thank you. - Ascalonian
No comments at all? - Michael Myers
I guess so (no comments). They really make things too easy in most languages. Anyway, we already have a perl answer with no comments. - Assaf Lavie
@Ben: I was going to mention that I saw that some time ago. Kudos for actually providing a link to it. (Of course, in that case, each line is a palindrome, not the entire program, as the OP seems to want.) - RobH
If someone can do it in Java, I'll be very impressed. I've been trying it, and it seems like it might be possible, but I can't quite get it. It seems like there's a principle that would make this a trivial problem; but I just can't put my finger on it. - Michael Myers
I'd be surprised if there's a way to end a source file with "ssalc cilbup" ;-) I suspect this might be impossible in a syntactically strict language like Java, but who knows... - David Z
@David: Java permits empty statements outside of class definitions, so you could start your class ";class tni" and end with "int ssalc;" -- if, of course, you could have variables outside classes. Still working on it... - Michael Myers
It seems to me that anything with balanced open/close delimiters is doomed, because { reversed is not }. - Steven Huwig
@Steven, I'm not so sure. C/C++ can handle it with macros (though there's still a problem with getting the macro reversal right). - Assaf Lavie
I'll believe it when I see it ;) - Steven Huwig
(4) Question closed as "not a real question"? Excuse me? - Assaf Lavie
(4) I wonder if it is possible to do it without throwaway code. - Angel
(10) Next up on Iron Programmer: A palindrome quine. - Jeff M
Quote from cited Wikipedia article : "(the adjustment of punctuation and spaces between words is generally permitted)" - Benjol
Ha, I learned today there's something called an ambigram: en.wikipedia.org/wiki/Ambigram Now That would have been a challenge. - Assaf Lavie
Sad that a tremendously popular question with 50 answers and 11K views, which is also a valid programming related puzzle (like many other such questions on SO) gets closed down. I think it says something really bad about some of the people in the community. I hope it gets re-reopened. - Assaf Lavie
The plea to re-open is not part of the question, please only put text pertaining directly to the question inside the question itself. - Adam Davis
Or, in other words, meta information about the question should appear in comments. - Adam Davis
@Adam, I only wrote it as part of the question because of the suggestion in this discussion: stackoverflow.com/questions/457088/… Naturally I was going to remove the request once it was reopened (and thanks for doing it for me). - Assaf Lavie
Why do the brackets / parents need to be reversed? Isn't a palindrome the same characters in reverse order? (and sometimes ignoring punctuation, like in "Able was I, ere I saw Elba.") - John
@John: The ORDER of characters must be reversed. Not the characters themselves. () in reverse order is )(... - Artelius
What, no Beatnik? Must... resist... - Russ
[+267] [2009-03-18 21:34:24] David Z

In a language that shall not be named [1]:

++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
<.<.<.<.<.<.<.<.<.<.<.<.<.<
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++
>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>++++++++++
[1] http://www.muppetlabs.com/~breadbox/bf/

(1) How did you ever manage to come up with that? Is it original? - Michael Myers
(3) Just trial and error... it wasn't that hard, it just took a little time. It's original as far as I know. - David Z
(2) Looks like "BrainF*ck" - Cory
Why do you think I didn't name it ;-) But yes, Brainf*ck it is. - David Z
Sir, that is amazing. That is a nice strategy for making brainf*ck palindromes. - Chris Lutz
(31) (Brain)F*ckin brilliant - GvS
(1) Wow. Just awesome. This deserves to be #1. - Epaga
(8) I'm tempted to take this extreme upvoting as a sign that I should attempt a smaller solution in the same language. - Chris Lutz
Who knows what people will go for ;-) I bet there are shorter solutions out there waiting to be discovered - I never tried to find them though. - David Z
+1 Very good. I can't decide whether this is better than the binary one, though. - Eduardo León
Massive respect. - Daishiman
+1 for using bf ;) - Gambrinus
How is this a palindrome with this string in the middle: "<.<.<.<.<.<.<.<.<.<.<.<.<.<"? Maybe there's a problem with my browser? - Argalatyr
(1) That string itself is a palindrome. And everything before it is the reverse of everything after it. So the whole program is a palindrome. - David Z
Bravo sir, bravo. - Malaxeur
Man. You got way too much time! ;3 - Xavier Ho
(1) Someone should give this a go in Whitespace‌​. - Spycho
I came up with a game! Let's all try to keep the votes at exactly 222! - Lambda Fairy
@DavidZaslavsky : Respect. - shobi
1
[+194] [2009-03-19 05:07:31] ephemient

I started from Tiny Programs [1] and wrote my own assembly. Sure, maybe it can be reduced further, but I don't know which other ELF header fields I can subvert for use as code while still being portable.

$ wc -c hellolleh
245 hellolleh
$ xxd hellolleh
0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 0300 0100 0000 5000 9331 2c00 0000  ........P..1,...
0000020: 0000 0000 0000 0000 3400 2000 0100 0000  ........4. .....
0000030: 0000 0000 0000 9331 c040 cd80 f800 0000  .......1.@......
0000040: 7401 0000 0700 0000 0010 0000 f7d8 ebe6  t...............
0000050: 686f 726c 6468 6f2c 2057 6848 656c 6cb8  horldho, WhHell.
0000060: 0400 0000 bb01 0000 0089 e1ba 0c00 0000  ................
0000070: cd80 bb00 0000 00e9 baff ffff bae9 0000  ................
0000080: 0000 bb80 cd00 0000 0cba e189 0000 0001  ................
0000090: bb00 0000 04b8 6c6c 6548 6857 202c 6f68  ......lleHhW ,oh
00000a0: 646c 726f 68e6 ebd8 f700 0010 0000 0000  dlroh...........
00000b0: 0700 0001 7400 0000 f880 cd40 c031 9300  ....t......@.1..
00000c0: 0000 0000 0000 0000 0100 2000 3400 0000  .......... .4...
00000d0: 0000 0000 0000 0000 2c31 9300 5000 0000  ........,1..P...
00000e0: 0100 0300 0200 0000 0000 0000 0000 0101  ................
00000f0: 0146 4c45 7f                             .FLE.
$ file hellolleh
hellolleh: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, corrupted section header size
$ ./hellolleh
Hello, World

(You can use xxd -r to load this hexdump back into a binary file.)

[1] http://www.muppetlabs.com/~breadbox/software/tiny/

(7) That is a feat of genius. - Chris Lutz
Wow! Very impressive! +1 - Eduardo León
Wow ! +1 - Learning
2
[+115] [2009-03-18 19:30:40] cobbal

cheating by comments in a shell script of your choice (bash for me)

echo 'hello world' # 'dlrow olleh' ohce

Edit:

And using the preprocessor in c you can use

#define foo fidne#
#include <stdio.h>

int main() {
    printf("hello world\n");
}

#if 0
0 fi#
}
;)"n\dlrow olleh"(ftnirp    
{ )(niam tni

>h.oidts< edilcni#
#endif oof enifed#

Edit: updated C code to remove all warnings in gcc (still one in Comeau though)
updated C code to be palindrome (thanks Can Berk Güder)

Edit:

And the simple, elegant, elisp solution

(message "%s" "hello world")'("dlrow olleh" "s%" egassem)

Although this is not a strict palindrome as I had to reverse parens


damn, I should have thought of that. - Assaf Lavie
(12) I don't think comments should count ;D - Element
I agree. No comments. Though hat's off to cobbal for the quick thinking. - Assaf Lavie
cobbal, your C program does not compile. I tried with Comeau. - Assaf Lavie
gcc compiled it for me, it did give a warning though - cobbal
"ComeauTest.c", line 15: error: extra text after expected end of preprocessing directive #endif enifed# - Assaf Lavie
take off strict mode and it just spits out warnings - cobbal
@cobbal, yea. but no fair. It's not a valid program according to the Standard AFAIK. - Assaf Lavie
)(main int should be )(niam tni - Can Berk Güder
The C one still has an error in comeau: "ComeauTest.c", line 15: error: extra text after expected end of preprocessing directive #endif oof enifed# ^ - Assaf Lavie
+1 very ingenious with the C ;-) - David Z
The second "%s" in the elisp example should be "s%" - Stephan202
fixed now, thanks - cobbal
The preprocessor trick is great! - Frank
Valid is subjective - maybe 'valid' to cobbal is 'compiles, runs, and produces expected output' - Erik Forbes
unfortunately the spec does specify that #endif must be followed by a new line :( - cobbal
Relaxing the comment requirement a little, insert // between foo and fidne (and between endif and oof) to make it valid C++. - Iraimbilanja
"the spec does specify that #endif must be followed by a new line" Yes, but a LOT of code out there in the real world has extra text after the #endif, and nearly every C compiler (other than Comeau, apparently) will allow it. - Mark Bessey
You sir are the definition of cheeky. - Lela Dax
3
[+102] [2009-04-08 14:53:29] falser

Pseudocode:

Output "Hello, World".
Ignore the two next lines.
.senil txen owt eht erongI
."dlroW ,olleH" tuptuO

LOL! that is a good cheat hahah! - Chii
(14) Made me laugh :) - Kuroki Kaze
(1) Well actually, this would work in Perl, with __END__ or =cut :) - ephemient
hehe. this is silly. - flies
(4) +1, its the only answer i understood lol - lock
4
[+99] [2009-03-19 00:07:18] Mark Stock

In the Machine Language Monitor on an Apple //e, type N300G003N to run this program:

300: A2 0C BD 0B 03 20 ED FD CA D0 F7 60 E4 EC F2 EF D7 A0 AC EF EC EC E5 C8 8C 5E CE CE FE CA 0A 7D FE 2F CE 4E 06 7F 0D AC DF DE 02 30 B0 DB C0 2A :003

From AppleSoft BASIC, PRINT "Hello, World" : END : DNE : "dlroW ,olleH" TNIRP - Mark Stock
(22) +1 for answer. I wish I could give another +1 for it being on the Apple ][e. - Beska
5
[+81] [2009-03-18 19:43:27] Miles

Perl:

print + "Hello, World\n";"n\dlroW ,olleH" + tnirp

+1 ... what does Perl interpret the +tnirp to be? - David Z
Nice. I had a hunch a Perl answer will not be late in coming. - Assaf Lavie
Strictly speaking, the second ; is unnecessary - it's still a palindrome and it still runs properly. And, honestly, a Perl answer should be a one-liner, shouldn't it? - Chris Lutz
(6) @David: since "tnirp" is not a function, it evaluates to the string "tnirp". Since "+" is a numerical operator, both strings are evaluated in numerical context (to zero). The 2 zeroes are added together, and the result is not used for anything (i.e. thrown away). - runrig
@Chris Lutz: you're absolutely right :) - Miles
(1) using 'say', you could shorten this guy by 8 characters. :) - Robert P
Could you? I'm not running Perl at this computer, but it looks like the + is essential to make this a valid program, as opposed to something that spits out the output and then fails. - David Thornley
(5) @Robert P - You could, but then you'd have to add "use feature 'say';" at the beginning. And ";'yas' erutaef esu" at the end. You lose more than you gain. - Chris Lutz
@runrig: Works for me (perl 5.8.8). It appears that unary + is a nop on strings. - Stewart
6
[+66] [2009-03-19 21:50:35] ephemient

Haskell. Actually pretty easy :)

main = putStr hw
hw = const "Hello, World" ab
a = ba ; niam = main ; ab = a
ba "dlroW ,olleH" tsnoc = wh
wh rtStup = niam

Or, in a comment by Reid Barton:

main = putStr `id` "Hello, World"
niam = main
"dlroW ,olleH" `di` rtStup = niam

Another variation:

main = const putStr main "Hello, World" where erehw "dlroW ,olleH" niam rtStup tsnoc = niam

(3) +1 for declarative languages making this easier. - Steven Huwig
(1) good thing haskell doesn't need so many parenthesis :) - VoidPointer
(6) A shorter solution: main = putStr `id` "Hello, World" ; niam = main ; "dlroW ,olleH" `di` rtStup = niam - Reid Barton
@Reid Barton: Wow, I totally didn't think of that trick at all. You're awesome! - ephemient
Wow, i didn't know you could do that in haskell @_@". Living and learning. - Alessandro Stamatto
7
[+53] [2009-03-18 22:00:02] David Z

Python 2.5:

'''dlroW ,olleH' tnirp
'''
print 'Hello, World'''

brilliant! I was trying to make something like this, but I couldn't get it working - cobbal
Nice, I was thinking that a Python solution wouldn't be possible. You can shorten it to three lines though: keep the middle line the same, and make the first line '''dlroW ,olleH' tnirp - Miles
Nice observation... edited in, thanks ;-) - David Z
(3) One liner version """dlrow ,olleH" tnirp;""";print "Hello, world""" - gnibbler
(2) Do docstrings count in the "no comments" rule? - dan04
8
[+51] [2009-03-18 20:03:15] Johannes Weiß

That should work on most shells (sh, bash and (thanks to Paulius Maruška) even in Windows ;-) ):

echo Hello World || dlroW olleH ohce

proof (the key is the lazy evaluation if echo Hello World succeeds, which does):

$ echo Hello World || dlroW olleH ohce
Hello World

Another one in sh/bash:

   alias dlroW=true saila=true
echo Hello World;dlroW olleH ohce
   eurt=alias eurt=World saila

EDIT: My old one (in bash, too) was not correct:

cat <(echo Hello World >&2;2&> dlroW olleH ohce)< tac

is no palindrome since the brackets are the wrong way and it needs a file called tac in the actual directory.


(2) very nice, tac must be a file though - cobbal
very nice indeed - Assaf Lavie
+1 for not using comments - Ferruccio
love the alias one, very creative - cobbal
But can you make it a haiku? ;) - Michael Myers
You should update your answer, because the unix shell things works very nicely on Windows command prompt too. :) - Paulius
mmyers: hmm, a haika get's difficult since I can't even pronounce dlrow so it gets difficult to count syllables. Paulius Maruška: Thanks! I did :-) - Johannes Weiß
9
[+30] [2009-03-19 12:45:59] IfLoop

Here's my answer in TCL:

proc unknown args {puts "Hello World!"}
}"!dlroW olleH" stup{ sgra nwonknu corp

Gotta love a language where the quote rules are really more guidelines than rules. The very fact that line 2 makes no sense causes line 1 to greet the user.

Actually, i think the proc unknown mechanism in tcl is really helpful in some cases and I miss it in other languages.


(1) So basically that's saying that if the interpreter can't understand something, it should 'puts "Hello World!"' ? Very clever! - Michael Myers
Myfirst version just had a return for the uknown, and it just ignored the palindrone crud. Im completely pleased to put the garbage to work. - IfLoop
(8) Also, I learned that I can name a proc }"dlroW . Show me another language where that's legal -- and I'll show you two brain-damaged languages! - IfLoop
This isn't a palindrome. The second pair of braces are opposite. - Lucas Oman
(1) @Lucas Oman: Actually, they are not. If you reverse the second line, the 'backwards' braces become forward. Many other answers to this question make that mistake. - IfLoop
Since the question is closed I'll put my Tcl answer here. Not as elegant as the above "unknown" trick through. puts \110ello,\x20World;\151f 0 f151\;dlroW02x\,olle011\ stup - Hugge
@TokenMacGuy: OK, I'll show you Forth, where : ? . ! ; is typically part of the language. - David Thornley
(2) puts Hello\ World;#;dlrow \olleH stup though it makes me feel dirty using a comment. Not as much as voting for that abortion of a solution would though. (Damnit, I'm a Tcl developer! I refuse to endorse ugliness in my creations!) - Donal Fellows
10
[+27] [2009-03-18 20:41:08] Sebastian Krog

In common lisp (using no comments or syntactic sugar). Prints only "Hello World!" and returns NIL.

(let (tel etouq)
  (let (tamrof etouq)
    (format t "Hello World!"
            "!dlroW olleH" t tamrof)
    (quote format)
    tel)
  (quote let)
  tel)

(12) Not a palindrome (your parentheses aren't reversed). - Michael Myers
(1) Your right! It is awfully hard to fix, though. Another language will have to do! - Sebastian Krog
(9) actually, I think that makes it more palindromic somehow, it's almost a mirror image - Ferruccio
I don't remember how format works, but couldn't you reduce that to: (format t "Hello World!" "!dlroW olleH" t tamrof) - Ferruccio
No, because "tamrof" at the end of your function call is a symbol with no reference. - Sebastian Krog
Using a quote character (like cobbal did in his elisp above) easily reduces the size, but it feels sort of like a comment trick to me, so i spent quite some time getting around it. - Sebastian Krog
There's a new challenge: making a Hello, World program that's a mirror image of itself! - Stewart
11
[+25] [2009-03-18 19:33:48] David Z

Surprise surprise, Jon Skeet has done that [1] ;-)

[1] http://stackoverflow.com/questions/284797/hello-world-in-less-than-20-bytes/284898#284898

(33) Am I the only one who thought Skeet's answer there was incredibly lame? Sorry, I must've missed the fanboy bus ;) - ojrac
(1) Maybe... it's kind of funny. At least the first time you see it. (It's not just because it's Jon Skeet!) - David Z
(7) I thought it was lame from the first time on. :) - ypnos
I do agree with ojrac (and I did see the answer in the first time). Nevertheless, Mr. Skeet answers usually are great. - Alex. S.
(13) Jon Skeet's solution does not, in fact, solve the problem given. It prints "Hello World", not "Hello, World". - ChrisA
(2) @ojrac: no you aren't - John Smith
12
[+22] [2009-04-08 15:00:21] falser

Befunge [1]

0"dlroW ,olleH"v<
@_,^         >#:^
^:#>         ^,_@
<v"Hello, World"0
[1] http://en.wikipedia.org/wiki/Befunge

(9) befunge makes such pretty code. this code, in addition to being a palindrome, is also symmetric about the origin! - IfLoop
13
[+19] [2009-03-19 00:26:35] Mark Stock

In HQ9+ [1],

H

edit:

As the challenge clearly notes, the output has to be exactly "Hello, World" whereas HQ9+ prints "Hello, world!" and so here is a special version of HQ9+ written in C [2] that when compiled will output exactly "Hello, World" using the following command:

./hq9 "" -9qH H one letter palindrome
[1] http://www.cliff.biffle.org/esoterica/hq9plus.html
[2] http://hoop-la.ca/software/hq9/hq9.c

aww, beat me to it! glad i thought to check the comments for hq9+ before posting :) - Martin DeMello
14
[+19] [2009-08-28 13:28:58] Artelius

I wanted to code a C solution that doesn't use #if or #ifdefs because I think of them as just another form of comments.

So! Here is my attempt, completely free of comments, #ifs and #ifdefs.

I used gcc 4.3.2, with the -Wall flag; it compiled without warnings or errors.

 
#define niam ){printf("Hello, World\n");return 0;}x(( z enifed#
;int(y);
#define x(x)
#include <stdio.h>
#define tni 0)
#define y int y=
int main(niam tni
=y tni y enifed#
)0 int enifed#
>h.oidts< edulcni#
)x(x enifed#
;)y(tni;
#define z ((x};0 nruter;)"n\dlroW ,olleH"(ftnirp{) main enifed#
 

15
[+18] [2009-03-18 21:40:41] Sebastian Krog

Or in yet another language that shall not be named [1]:

"!dlroW olleH">:#,_@_,#:>"Hello World!"

[1] http://quadium.net/funge/spec98.html

Any Befunge program deserves respect. :-) You might want to use different tags or something to prevent Stackoverflow's syntax highlighting from making everything look like a comment. - ShreevatsaR
This is technically not a valid palindrome in Befunge. Befunge(93) programs require an 80x25 instruction grid, meaning if you simply placed your code at 0,0 there would be 24 empty rows of NOOPs (whitespace), so it would be a palindrome vertically. - Loren Segal
There's nowhere in the original specification where a full 80x25 grid is required as input, it is merely represented as such by the interpreter/compiler. - Sebastian Krog
Besides, this is written in Funge-98, which doesn't have the fixed grid size of Befunge-93. The program does also work in Befunge-93, but that's another matter. - Stewart
16
[+18] [2009-03-24 19:08:34] jtxx000

Shortest yet (in TeX):

Hello, world\end dne\dlrow ,olleH

Wow, it's even shorter than the APL solution! - ephemient
(1) Should the slashes be reversed, since the parens are? - John
(2) @John no, the parens aren't mirrored - example palindromes Hello/-/olleH or Hello(-(olleH - Pool
17
[+16] [2009-03-18 19:38:02] Aistina

C++

Not sure if this is considered cheating or not :P

int main() //
{ // }
  // ;0 nruter
  printf("Hello, World"); // ;)"dlroW, olleH"(ftnirp
  return 0; //
} // {
// )(niam tni

(3) Parens should be reversed in the comments. - RobH
The soliduses (slashes) need to be reversed too. - Broam
18
[+15] [2009-03-24 23:09:11] Dietrich Epp

And people say this is hard in python (edited, didn't see the "no comments" rule)...

" \"" and print('Hello, world') and " dna )'dlrow ,olleH'(tnirp dna ""\ "

I challenge anyone to do better: this not only is one line, but it returns None so you don't get any extra output if you type it into the Python REPL.


(1) Py3k? My Python 2.5.4 doesn't like print as a function. - ephemient
+1 for figuring out the backslash thing. - IfLoop
Python 2.x version (one line): " \"dna enoN;'dlrow olleH'tnirp;enoN dna"and None;print'Hello world';None and"\ " - Markus Jarderot
(1) One line, Python 2.x, 73 characters: " \""and None;print 'Hello, world'or"ro'dlrow ,olleH' tnirp;enoN dna""\ " OR, if you don't care about the return value, 57 characters: " \"";print 'Hello, world'or"ro'dlrow ,olleH' tnirp;""\ " - Dietrich Epp
19
[+15] [2009-09-18 22:06:05] Stewart

Someone had to do it eventually....

PLEASE,1<-#12DO,1SUB#1<-#238DONOTODPUEVIGOD1,TUODAERESAELPDO,1SUB#2<-
   #108DON'TONOD61#-<21#BUS1,ODPLEASE,1SUB#3<-#112DON'T'NOD42#-<11   
       #BUS1,ODO,1SUB#4<-#0DONOT'NESAELP861#-<01#BUS1,ODO,1SUB       
            #5<-#64PLEASENOTONOD442#-<9#BUS1,ODO,1SUB#6<-            
                 #194DON'TONOD62#-<8#BUS1,ESAELPDO,1                 
                    SUB#7<-#48DON'T'NOD84#-<7#BUS                    
                 1,ODPLEASE,1SUB#8<-#26DONOT'NOD491#                 
            -<6#BUS1,ODO,1SUB#9<-#244DONOTONESAELP46#-<5#            
       BUS1,ODO,1SUB#10<-#168PLEASEN'TONOD0#-<4#BUS1,ODO,1SUB#       
   11<-#24DON'T'NOD211#-<3#BUS1,ESAELPDO,1SUB#12<-#16DONOT'NOD801#   
-<2#BUS1,ODPLEASEREADOUT,1DOGIVEUPDOTONOD832#-<1#BUS1,OD21#-<1,ESAELP

dare I ask what language this monstrosity is in? - IfLoop
(1) C-INTERCAL. intercal.freeshell.org - Stewart
(7) More languages should insist on politeness. - Chris J
20
[+14] [2009-03-25 03:49:03] Chetan Sastry

Basic (Someone had to do it)

10 PRINT "HELLO WORLD" : GOTO 20 : DNE 02
20 END : 02 OTOG : "DLROW OLLEH" TNIRP 01

Explanation: Basic is an interpreted language. The interpreter doesn't parse the source it doesn't need to. ':' is statement separator like ';' in C-like languages.

In fact this works too, it prints Hello World, but stops with an error.

10 PRINT "HELLO WORLD" : "DLROW OLLEH" TNIRP 01

Works for me on an Apple 2e emulator!. however, You don't have a palindrone. The last token is 10, but should be 01 for this to be a correct. Works though. - IfLoop
(5) Try 10 PRINT "HELLO WORLD" : END : DNE : "DLROW OLLEH" TNIRP 01 - IfLoop
Only applies to those BASICs for which "The interpreter doesn't parse the source it doesn't need to" is strictly true. Counterexamples include QBasic (parses all code before running, and I think compiles it internally) and Spectrum BASIC (doesn't allow syntax errors to be entered into the program). But you've got me wondering if it can be done in Spectrum BASIC.... - Stewart
@TokenMacGuy: To make your example 8 characters shorter <code>1 PRINT "HELLO WORLD":END:DNE:"DLROW OLLEH" TNIRP 1</code> Some BASICs might even let you remove 4 more spaces. - Stewart
21
[+10] [2009-03-18 20:41:01] Michael Myers

Here's what I have so far in Java:

//}
;class tni
/*//;"*/{ public static void main(String[]gnirtS) { /*"
+"*/System.out.println(new StringBuilder().toString()+'H'+'e'+'l'+'l'+'o'+','+' '+'W'+'o'+'r'+'l'+'d'); /*"
+"*/} /*"
+"*/String gnirtS = " = String gnirtS/*"+
"*/ }/*"+
"*/ ;)'d'+'l'+'r'+'o'+'W'+' '+','+'o'+'l'+'l'+'e'+'H'+)(gnirtSot.)(redliuBgnirtS wen(nltnirp.tuo.metsyS/*"+
"*/ { )String][gnirtS(niam diov citats cilbup {/*";//*/
int ssalc;
}//

Only one of the comments is in violation of the spirit of the rules: the //} at the very start. The rest are just to mask newlines; I could take them out if I wrote the main part of the program on one line.

The center of the palindrome is the quotation mark: String gnirtS = "

I'm pretty sure it's actually a palindrome. What's the easiest way to check?

EDIT: It wasn't quite, but now it is.


(4) equal(reverse(s), s)... - Assaf Lavie
22
[+9] [2009-03-19 16:08:02] ephemient

Perl, inspired by the awk [1] and php [2] solutions:

BEGIN{print"Hello, World";exit}tixe;"dlroW ,olleH"tnirp{NIGEB

It exits before it discovers that the remainder of the file doesn't make any sense.

[1] http://stackoverflow.com/questions/659752/660085#660085
[2] http://stackoverflow.com/questions/659752/662175#662175

+1 for extreme cleverness. - Chris Lutz
you're missing a { in the middle it seems :D - user51568
@stefan: In an odd length palindrome such as this, the middle character doesn't need a matching character. Besides, a { would be a mirror image character to the }. - RobH
For the record, I think he could add in a } after the middle } and it would work all the same - Perl should ignore it just as well. Although a "\n" at the end might be nice. - Chris Lutz
23
[+9] [2009-03-24 20:29:14] mernen

Ruby:

puts %"Hello, World!" || "!dlroW ,olleH"% stup

Shorter p %'Hello, World' % 'dlroW ,olleH'% p - Jonas Elfström
24
[+9] [2009-03-25 05:24:41] Brian Campbell
"Hello, World" || "dlroW ,olleH"

This is an even shorter variation on several that we've seen already. The interesting thing about this one is that it works in several languages, depending on your interpretation of the rules (whether quotes are allowed to be printed out or not):

Javascript, as executed in the Spidermonkey interpreter:

$ js
js> "Hello, World" || "dlroW ,olleH"
Hello, World

Ruby:

$ irb
irb(main):001:0> "Hello, World" || "dlroW ,olleH"
=> "Hello, world"

25
[+8] [2009-03-18 21:28:35] Gaetan Dubar

In Ruby,

tcepsni = puts "hello world!" || "!dlrow olleh"
stup = inspect

(argg, there's a newline)


Just change to print then. print %"Hello, World!" || "!dlroW ,olleH"% tnirp - Jonas Elfström
26
[+8] [2009-03-19 15:56:40] ephemient

J [1], no comments.

1!:2&2['Hello, World'['dlroW ,olleH'[2&2:!1
[1] http://www.jsoftware.com/

(2) Again, the brackets and parentheses aren't reversed. It's sort of a mirror image this way, except for all those other characters. - Michael Myers
Fixed. Actually, that made it shorter.... - ephemient
Ah, thanks for the typo fix (indeed it was). - ephemient
27
[+6] [2009-03-25 07:42:23] Anonymous

Python 2.x:

"t\";]41:1[";print"\tHello, World..dlorW ,olleHt\"tnirp;"[1:14];"\t"

@Dietrich Epp: 5 characters shorter.


i KNEW there was some kind of solution using backslash escapes, but couldn't make my head do it. +1 - IfLoop
28
[+5] [2009-03-24 21:04:17] Darc

In APL [1] :

'Hello World!',13↓31,'!dlroW olleH'

And within a dynamic function (only in Dyalog APL dialect) :

⍬{'Hello World!',13↓31,'!dlroW olleH'}⍬

Of course, again the brackets make it a mirror image rather than a strict palindrome.

[1] http://www.dyalog.com/

Of course, APL would have an easy way to do it. :-) - RobH
Even better than my J solution... man I wish I had an APL interpreter :) - ephemient
Actually, does this write to stdout (1!:2 in J) or just return the string (which gets printed by the REPL)? - ephemient
29
[+4] [2009-08-28 11:17:42] Stewart

Another language that cannot be named [1], albeit in a different sense:

100 108 114 111 87 32 44 111 108*101 72!!!!!!
!!!!!!27 101*801 111 44 23 78 111 411 801 001
[1] http://wwwep.stewartsplace.org.uk/languages/tlwnn/

30
[+4] [2009-09-12 00:17:34] Markus Jarderot

Lua

x=print"Hello, world"=="dlrow ,olleH"tnirp=x

31
[+4] [2009-10-29 04:15:57] KirarinSnow

PostScript, no comments, 41 chars:

(Hello, World)= quit tiuq =)dlroW ,olleH(

The interpreter stops parsing after quit ... the rest of it is syntactically ill-formed. Here's a version that runs until the end (135 characters):

[/Hello,!World/ pop 12 string/ pop cvs/ pop
dup/ pop 6 32 put/ pop = pop /tup 23 6 pop /pud
pop /svc pop /gnirts 21 pop /dlroW!,olleH/[

The fact that strings are delimited by nonidentical characters (parens) makes this a bit harder. Ironically, one can get around this by using pop in the right places; pop itself is quite coincidentally (and usefully so) a palindrome. ☆^_^☆

pop is quite a lifesaver, actually. I'm not sure how this would be possible if the operator's name weren't a palindrome. :o

Here's a slightly longer version without pop (180 chars):

[/dlroW!,olleH/x/tup/x/pud/x/svc/x/gnirts/Hello,!World
12 string cvs dup 6 32 put =/nigeb>>begin/= tup 23 6 pud svc gnirts 21
dlroW!,olleH/string/x/cvs/x/dup/x/put/x/Hello,!World/[

32
[+3] [2009-03-18 20:09:44] Mark T

Write in "in your language of choice" leaves a pretty big hole. My language of choice for this problem is a home-brew language consisting of one command. So here is the code calling that one command:

HelloolleH

Of course what that command does is print Hello World.


See David's answer referring to Jon Skeet's one-character program. - Michael Myers
1 point for originality. However you must submit your compiler, too :) - gbarry
(7) And the compiler must also be a palindrome! - Chris Lutz
ha ha, pretty hard if you also provide the palindrome code of your palindrome compiler to compile itself to a palindrome binary... - Alex. S.
@Alex - I thought the palindrome binary was a bit high of a requirement, since you'd basically have to write it in assembly to get that effect, but hey. - Chris Lutz
(8) please post your compiler gzipped - the zipped file of course being a palindrome! - petr k.
@petrk. is it possible? In all seriousness. - Annan
33
[+3] [2009-03-19 13:22:52] Gumbo

Using comments:

/**/print"Hello, World!";/*/"!dlroW ,olleH"tnirp/**/

unexpected string Unexpected 'trnip'. At line #2 - Kuroki Kaze
I could swear it did work. But I now used comments instead. - Gumbo
34
[+3] [2009-03-24 18:35:01] jtxx000

Io [1]:

forward   :=  method
"Hello, world" print
tnirp "dlrow, olleH"
dohtem  =:   drawrof
[1] http://iolanguage.com/

35
[+3] [2009-03-24 19:03:32] hasenj

here's my language:
a is equivelant to white space
b prints "Hello, world"

so here's the program:

aaaaaaa
aaaaaaa
aaaaaaa
aaabaaa
aaaaaaa
aaaaaaa
aaaaaaa

Maybe a new rule should be implemented: No made up languages. :-) - RobH
(1) Or you have to provide the interpreter/compiler too :) - ephemient
(3) Every language was made up at some point in history. - Stewart
+1 for a creative solution - Joe D
Does your language compiles in your language? - Luka Rahne
@ralu sure theoretically I can add more symbols to make the language turing-complete and then it will be possible to write a compiler for the language in the language itself. - hasenj
36
[+3] [2009-03-25 02:14:36] qwerty

mIRC Script:

//echo Hello, World | alias dlrow noop poon world saila | dlroW ,olleH ohce//

37
[+3] [2009-03-25 06:07:10] Mike Samuel

Javascript:

(alert)('Hello, World') && ('dlroW ,olleH')(trela)

Not a palindrome: the parens need to be reversed. sorry. - Assaf Lavie
Quite right. Here's one that works i = null i/=document.body.innerHTML = 'Hello, World',0/ /0,'dlroW ,olleH' = renniLMTH.ydob.tnemucod=/i llun = i - Mike Samuel
Ack. It ate my formatting. There should be newlines after "null", after ",0/", and after "=/i". - Mike Samuel
maybe not, but I like it. - hasenj
38
[+3] [2009-03-25 07:22:37] Adrian Quark

Orc [1]: "hello world" << "dlrow olleh"

The "<<" runs both the LHS and RHS in parallel, but only returns the value of the LHS, which the interpreter prints. Follow the Orc link to learn more about Orc (there is a "Try Orc" link where you can run this program yourself).

[1] http://orc.csres.utexas.edu

(1) but the "<<" make it not a palindrome, no? - Assaf Lavie
39
[+2] [2009-03-18 20:00:56] Assaf Lavie

Help. I got this far in C++ (using macros). So I'm posting this as a wiki and welcoming help.

#define x // fidne# 

#include <iostream>
int main() { std::cout << "Hello, World\n"; }
#ifdef N
N fedfi#
} ;"n\dlroW ,olleH" << touc::dts { )(niam tni
>maertsoi< edulcni#

#endif // x

40
[+2] [2009-03-18 21:01:30] Steven Huwig

Awk:

BEGIN { print "Hello, World"; exit } { tixe ;"dlroW ,olleH" tnirp } NIGEB

/ \/ }{ / {} BEGIN { print "Hello, world"; exit } /\
\/ } tixe ;"dlrow ,olleH" tnirp { NIGEB }{ / {} /\ /

Old one did not work because of the braces. The new one uses regex literals to embed the reversed code.


not a palindrome, probably. Block delimiters kill this. - Steven Huwig
41
[+2] [2009-03-21 12:31:18] Andrea Ambu

Plain bash.

echo "Hello World" || "dlroW olleH" oche

42
[+2] [2009-03-25 14:51:51] Nick

Fortran:

      !DNE      
      PROGRAM PAL!      
      print *,'Hello World!' !      
      ! '!dlroW olleH',* tnirp      
      !LAP MARGORP      
      END!      

or the slightly shorter:

      !DNE
      print *,"Hello, World"!
      !"dlroW ,olleH",* tnirp
      END!

43
[+2] [2009-08-28 10:47:49] Stewart
<?php ">?tixe;";echo 1?"\x48ello, World":"dlroW ,olle84x\"?1 ohce;";exit?>" php?<

<?php echo 'Hello, World';//\\'Hello, World';php?< Is this a palindrome? - Nouphal.M
44
[+2] [2009-10-29 07:06:58] gnibbler

Golfscript - 29 bytes

"dlrow ,olleH";"Hello, World"

';' means pop and discard


golfscript.com - Assaf Lavie
45
[+1] [2009-03-19 00:33:26] Andrea Ambu

In python 2 lines:

tnirp = 'Hello, World' # print tnirp
print tnirp # 'dlroW ,olleH' = print

can be wrote in 3 lines........


Now, can you do the same without comments? :) - ephemient
It would be challenging, I'll try, for now I did it in plain bash :D - Andrea Ambu
Erm, if you go with comments: print('Hello, World') # )'dlroW ,olleH'(tnirp - sebnow
it's the same :) - Andrea Ambu
46
[+1] [2009-03-21 01:41:37] IfLoop

Python is really tough. Here's the best I can do.

"hello world"
tnirp, fi = True, __doc__#
if tnirp:print fi
#__cod__ ,eurT = if ,print
"dlrow olleh"

47
[+1] [2009-03-24 19:08:47] joke

Common Lisp:

(or' "Hello, World" "dlroW ,olleH" 'ro)

Both shortest and simplest one? SBCL + Slime:

"dlroW ,olleH""Hello, World"

Not quite a palidrome, since the last character is not the same as the first character. - Michael Myers
(1) MHO: As a valid Lisp program, it has to start and to end with a paren, and in between there are no parens. No rule on earth is absolute. You have to know when (intelligently) to add an exception to a rule. - joke
48
[+1] [2009-03-25 06:19:09] Ezran

Ruby:

;puts 'Hello! World'.tr'!,;q%,',%q;,!'rt.'dlroW !olleH' stup;

I was really hoping to find a way to make good use of the second half (string) rather than having it sit there just like if I had added a comment... But so far I've only got it fixing the exclamation into a comma...


49
[+1] [2009-04-08 14:49:48] falser

Unlambda:

`?d`?c`?d`?c`?d`?c`?d``v````````````.H.e.l.l.o.,. .W.o.r.l.di`d
```````````````
d`id.l.r.o.W. .,.o.l.l.e.H.````````````v``d?`c?`d?`c?`d?`c?`d?`

50
[+1] [2009-08-02 22:29:24] Peter Boughton

Here it is in CFML [1], without using comments:

<cfsetting enablecfoutputonly="true"/>
<cfoutput>Hello, World</cfoutput>
>tuptuofc/<dlroW ,olleH>tuptuofc<
>/"eurt"=ylnotuptuofcelbane gnittesfc<


Or, an extended version that would still work inserted into almost any page, even if global debugging is on:

>/trobafc<<cfcontent reset />
<cfsetting enablecfoutputonly="true" showdebugoutput="false" />
<cfoutput>Hello, World</cfoutput>
>tuptuofc/<dlroW ,olleH>tuptuofc<
>/ "esalf"=tptuogubedwohs "eurt"=ylnotuptuofcelbane gnittesfc<
>/ teser tnetnocfc<<cfabort/>
[1] http://opencfml.org/

51
[+1] [2009-09-12 01:09:22] mob

shell + Perl

perl -e 'print "Hello, World\n"' '"n\dlroW ,olleH" tnirp' e- lrep

Neat. Presumably the arguments following the -e program text get passed to the program. I bet this works for other UNIX tools, too... - Mark Bessey
52
[+1] [2009-09-18 23:23:50] Russ Bradberry

vbscript:

msgbox+"Hello, World"+y,00,y+"dlroW ,olleH"+xobgsm

53
[+1] [2009-10-29 03:45:43] KirarinSnow

sed, no comments, 51 characters:

;;s/.*\|;s/Hello, World/;q;/dlroW ,olleH/s;|\*./s;;

Give it anything as input: echo SOMETHING | sed -f thisfile.sed

The autocolorcoding looks pretty nice on this one. ☆^_^☆


54
[+1] [2010-03-26 10:03:31] luminarious

Representing REBOL [1]:

REBOL [] print "Hello world!" halt tlah "!dlrow olleH" tnirp [] LOBER
[1] http://www.rebol.com/

55
[+1] [2010-04-15 16:52:53] David

J

'Hello World!'['!dlroW olleH'

Easy - [ returns the left argument.


but no comments are allowed... - Assaf Lavie
(1) @Assaf: You're right - didn't see that. Edited and now it's even shorter! - David
56
[+1] [2010-11-30 23:22:34] Ante

It is not strictly a palindrome, but with omiting whitespaces it is :-)

Whitespace code:

H     
e            
l                 
l                     
o                    
,                           
.                       
W            
o            
r                 
l                           
d                     
. 
.                   
.              
.
.   
.   
d   
l 
r       
o
W 
. 
,
o   
l
l
e
H

More readable format, S-space, T-tab:

.SSSSS
.SSSTSTS
.SSSTTSSTSS     
.SSSTTSTTSS     
.SSSTTTSSTS             
.SSSTTSTTTT     
.SSSTSTSTTT     
.SSSTSSSSS
.SSSTSSSSS
.SSSTSTTSS              
.SSSTTSTTTT     
.SSSTTSTTSS     
.S
.SSSSTTSSTST    
.SSSTSSTSSS     
.
.SSS
.T
.SSS
.S
.TST    
.
.S
.S
.
.SST
.
.
.
.

57
[0] [2009-03-18 19:30:38] dmckee

If I write a normal hello world in c++ without comments or newlines and append a '/', then I have the first half of a working palindromatic program...

Ah, the #include causes a small problem


Like this:

#include <iostream>//
int main(void){std::cout<<"Hello, world!"<<std::endl;}/

I haven't tried C++, but I know that you can use printf in C without the #include, at least on some compilers. - ojrac
on all compilers -- just declare it. int printf(const char* s, ...); - Lou Franco
58
[0] [2009-03-18 19:33:54] Lasse V. Karlsen

Well, easy if you allow comments.

Just (pseudo-code for any language):

program-that-prints-hello-world // dlrow-olleh-strnirp-taht-margorp

Of course, if you disallow comments, then it becomes much harder.

Here's a C# version:

class P { static void Main() { System.Console.WriteLine("Hello world"); } } //
} };)"dlrow olleH"(eniLetirW.elosnoC.metsyS { )(niaM diov citats { P ssalc

Just put everything on the second line after // with a space in front.


yup, the comments do make it easier. so let's try it without them :) - Assaf Lavie
Well, I'd think that any language that uses braces will have a hard time then, as in the second half all the braces will be in the wrong order, just to take one problem at a time. - Lasse V. Karlsen
I agree. I'm trying it out in C++ and I fear I might have to resort to tons of macro magic to make it work. - Assaf Lavie
In C or C++, you're stuck with trying to end the program with ")niam tni". If I do something like "#define tni ;", I need to have a "; int enifed#" line somewhere, and '#' is not allowed in identifiers. - David Thornley
59
[0] [2009-03-18 19:55:36] Rayne
(println "Hello, World!") ; )"!dlroW ,olleH" nltnirp(

I cheat.


What language is that? - Michael Myers
any language, it prints before it throws an exception, ha - Shawn
Not a palindrome. The parens end up backwards, beginning with a closed paren and ending with an open paren. - Brian Carper
The language is Clojure, and he is right, I thought no one would notice :( - Rayne
(1) @Shawn No, this doesn't throw an exception. ; denotes a single line comment in Clojure. - Rayne
60
[0] [2009-03-25 01:22:47] tlrobinson

JavaScript (cheating):

alert("Hello world"); // ;)"dlrow olleH"(trela

61
[0] [2009-03-25 12:40:41] geniepro

yet another Haskell solution:

main = putStrLn "Hello World!" -- "!dlroW olleH" nLrtStup = niam


62
[0] [2009-04-03 14:13:20] falser

False (http://strlen.com/false/) (cheating)

0'}"Hello, world"{{"dlrow, olleH"}'0

63
[0] [2009-08-16 02:06:17] computergeek6

Python:

print "Hello, World" # "dlroW ,olleH" tnirp

not in the spirit of the 'no comments' rule. Not really in the letter either. - IfLoop
(1) The "no comments" rule wasn't there when I posted this. - computergeek6
64
[0] [2009-09-18 22:39:32] Russ Bradberry

HTML no comments :D

Hello, World<p style="display:none;">";enon:yalpsid"=elyts p<dlroW ,olleH

65
[0] [2012-07-06 19:33:04] hmmftg

I think somebody should do this!

In PL/SQL:

Begin --
   DBMS_OUTPUT.Put_Line('Hello, World'); --
End; --
-- ;dnE
-- ;)'dlroW ,olleH'(eniL_tuP.TUPTOU_SMBD   
-- nigeB

Thanks.


66
[-1] [2009-03-25 04:10:42] Keith Hill

Windows PowerShell:

"Hello World" # "dlroW olleH"

67
[-2] [2009-03-24 18:49:10] lorg

Since you allowed any language I want, I can cheat\b\b\b\b\bdefine a new language, in which the empty string translates to the program that prints out "hello world". Since the empty string is a palindrome, I present my solution in this language: "".


68
[-2] [2009-10-29 04:11:08] Imagist

Javascript:

alert("Hello, world");)"dlrow , olleH"(trela

I don't have time to test this out, but if I remember correctly, most browsers just stop executing the Javascript when an error occurs.


How can't you have the time? Just write "javascript:[YOUR CODE]" in the adress bar and hit enter. Besides, you're wrong, the browser first checks for syntax errors, and when any are found, the code is nort executed. - Vincent
69