118
\$\begingroup\$

There have been a couple of previous attempts to ask this question, but neither conforms to modern standards on this site. Per discussion on Meta, I'm reposting it in a way that allows for fair competition under our modern rulesets.

Background

A is a string that "reads the same forwards and backwards", i.e. the reverse of the string is the same as the string itself. We're not talking about "convenient palindromes" here, but a strict character-by-character reversal; for example, ()() is not a palindrome, but ())( is.

The task

Write a program or function that takes a string S (or the appropriate equivalent in your language) as input, and has one output Q (of a type of your choice). You can use any reasonable means to take the input and provide the output.

  • When the input S is a palindrome, the output Q should have a value A (that is the same for any palindromic S).
  • When the input S is not a palindrome, the output Q should have a value B (that is the same for any non-palindromic S).
  • A and B must be distinct from each other.

Or in other words: map all palindromes to one value, and all non-palindromes to another.

Additionally, the program or function you write must be a palindrome itself (i.e. its source code must be palindromic), making this a challenge.

Clarifications

  • Although true and false are obvious choices for A and B, you can use any two distinct values for your "is a palindrome" and "isn't a palindrome" outputs, which need not be booleans.
  • We're defining string reversal at the character level here; éé is palindromic regardless of whether the program is encoded in UTF-8 or Latin-1, even though it's not a palindromic sequence of octets after UTF-8 encoding.
  • However, even if your program contains non-ASCII characters, it only needs to work for ASCII input. Specifically, the input S will only contain printable ASCII characters (including space, but not including newline). Among other things, this means that if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification (unless your language's I/O encoding is very weird). As such, the definition of a palindrome in the previous bullet only really matters when checking that the program has a correct form.
  • Hiding half the program in a comment or string literal, while being uncreative, is legal; you're being scored on length, not creativity, so feel free to use "boring" methods to ensure your program is a palindrome. Of course, because you're being scored on length, parts of your program that don't do anything are going to worsen your score, so being able to use both halves of your program is likely going to be helpful if you can manage it.
  • Because the victory criterion is measured in bytes, you'll need to specify the encoding in which your program is written to be able to score it (although in many cases it will be obvious which encoding you're using).

Victory criterion

Even though the program needs to be a palindrome at the character level, we're using bytes to see who wins. Specifically, the shorter your program is, measured in bytes, the better; this is a challenge. In order to allow submissions (especially submissions in the same language) to be compared, place a byte count for your program in the header of your submission (plus a character count, if it differs from the number of bytes).

\$\endgroup\$
12
  • 13
    \$\begingroup\$ Would someone please explain why would ()() not be a palindrome?? \$\endgroup\$ Commented Feb 20, 2017 at 6:38
  • 67
    \$\begingroup\$ @EmilioMBumachar Try replacing ( with a and ) with b. Is abab a palindrome? No, it would have to be abba. Then ()() isn't a palindrome either; it would have to be ())(. \$\endgroup\$
    – DLosc
    Commented Feb 20, 2017 at 6:40
  • 7
    \$\begingroup\$ Those solutions entirely using comments to make the program palindromic looks like a loophole to me :( \$\endgroup\$
    – kennytm
    Commented Feb 20, 2017 at 8:26
  • 17
    \$\begingroup\$ @kennytm Disallowing them would be worse, because there's no satisfactory way to do that objectively in a language-agnostic way. (What's a comment? What about putting the unused half in a string literal that is discarded? What about 2D languages where you can have perfectly executable code that is simply never reached?) \$\endgroup\$ Commented Feb 20, 2017 at 9:08
  • 15
    \$\begingroup\$ ()() is not a palindrome, but ())( is. Congratulations, you made it onto reddit! \$\endgroup\$ Commented Feb 25, 2017 at 6:31

76 Answers 76

1 2
3
1
\$\begingroup\$

Julia 1.0, 33 bytes

!x=reverse(x)==x#x==)x(esrever=x!

Try it online!

  • A comment is used to make the source a palindrome
  • Returns true for the empty string
\$\endgroup\$
0
\$\begingroup\$

[Python], 84 bytes

lambda s:list(s)==list(reversed(list(s)))#)))s(tsil(desrever(tsil==)s(tsil:s adbmal 

Pretty simple, take the string s, convert it into a list of chars and then compare that against the reversed list of chars generated from the same string.

\$\endgroup\$
2
  • \$\begingroup\$ This answer is invalid because it isn't a palindrome itself. \$\endgroup\$
    – DJMcMayhem
    Commented Feb 20, 2017 at 21:38
  • 1
    \$\begingroup\$ @DJMcMayhem missed that caveat, but fixed now, unfortunately ugly. Helps clarify some of the other answers though ;P \$\endgroup\$ Commented Feb 20, 2017 at 21:43
0
\$\begingroup\$

SmileBASIC, 109 bytes

INPUT P$WHILE LEN(P$)>1P=P+(POP(P$)!=SHIFT(P$))WEND?!P'P!?DNEW))P$(TFIHS=!)$P(POP(+P==P1>)$P(NEL ELIHW$P TUPNI

Could definitely be shorter...

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

Perl 5, 69 bytes

$_=<>;chop;print 1 if reverse eq$_#_$qe esrever fi 1 tnirp;pohc;><=_$

Takes input via STDIN. Prints 1 if the input is a palendrome, otherwise exits.

\$\endgroup\$
1
  • \$\begingroup\$ A couple of hints: you could save quite a few bytes by just printing the boolean returned by eq directly; and you could request input with no trailing newline to avoid the need to call chop. \$\endgroup\$
    – user62131
    Commented Mar 28, 2017 at 22:32
0
\$\begingroup\$

REXX, 78 bytes

arg a
b="say a=reverse(a)"
interpret b
exit
tixe
b terpretni
")a(esrever=a yas"=b
a gra

I thought that early exit would leave the mirrored program uninterpreted, but at least Regina REXX complains about unbalanced parentheses, hence the INTERPRET workaround.

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

Kotlin, 32 bytes

Just another "boring" solution but in Kotlin :))

s.reversed()==s//s==)(desrever.s

Try it online!

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

RProgN 2, 5 bytes

]iei]

Returns -1\n-1 for true, 0\n0 for false.

Explained

]iei]
]       # Duplicate the top of the stack.
 i      # Reverse the duplicate
  e     # Are they equal? 1 if true, 0 if false.
   i    # Inverse calculates n*-1. Redunant.
    ]   # Duplicate. Redundant.

Try it online!

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

BASH, 52 bytes

[ "`rev<<<$1`" = "$1" ];$?$;] "1$" = "`1$<<<ver`" [

success output (run as palpal.bash:

~/workspace/golf $ bash palpal.bash "$(cat palpal.bash)"
palpal.bash: line 1: 0$: command not found
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: ]: command not found

failure output:

~/workspace/golf $ bash palpal.bash "hello"
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: ]: command not found

notice that first output line has either a 1 or 0 which are the return code of the actual palindrome check.

It's not much better than using a comment for the second half

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

C++ (gcc), 138 bytes

[](auto s){return equal(s.begin(),s.begin()+s.size()/2,s.rbegin());}//};))(nigebr.s,2/)(ezis.s+)(nigeb.s,)(nigeb.s(lauqe nruter{)s otua(][

Lambda using a builtin to check if the argument is palindromic. To make it palindromic, I had to add the entire source, reversed, in a comment. Not very creative, I know. Note that clang will not compile this.

Try it online here.

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

Gol><>, 31 bytes

iEv
?;>l2(q1h{-
-{h1q(2l>;?
vEi

Try it online!

iEv
?;>l2(q1h{-

iEv
i    Take input as a char
 E   If the last input was EOF, pop and execute next; otherwise, skip 1
iEv  Take all input and move to next line

>l2(q1h{-?;
 l2(         Is the stack length < 2? (1 if yes, 0 otherwise)
    q        If not, skip 2 commands (consume the top)
     1h      Print 1 and halt
       {     Rotate the stack (bottom goes to the top)
        -    Difference
         ?   If zero, skip one command (consume the top)
          ;  Halt without printing anything
\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 110 bytes

s=>Console.Write(new string(s.Reverse().ToArray())==s)//)s==))(yarrAoT.)(esreveR.s(gnirts wen(etirW.elosnoC>=s

Try it online!

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

Pascal (FPC), 139 bytes

uses strutils;var s:string;begin read(s);write(s=ReverseString(s))end.dne))s(gnirtSesreveR=s(etirw;)s(daer nigeb;gnirts:s rav;sliturts sesu

Try it online!

The program compares if the input is equal to its reverse using ReverseString() function from module strutils.

end. is the last part of the program. This program does not use comments because, in most cases, FPC does not care what is after end., so the program without the dot is simply reversed and appended to the program itself.

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

T-SQL, 70 bytes

SELECT IIF(s=REVERSE(s),1,0)FROM t--t MORF)0,1,)s(ESREVER=s(FII TCELES

Didn't see a SQL version, so here's my try. Returns 1 for a palindrome, and 0 otherwise. IIF is supported by SQL 2012 and later.

Input is via pre-existing table t with varchar field s, per our IO rules. The input table can include multiple rows.

The -- in the middle is a comment character.

Edit: Here's a more clever version, using a strangely-named input table instead of an extended comment. Unfortunately slightly longer (73 bytes):

--"
SELECT IIF(s=REVERSE(s),1,0)FROM"MORF)0,1,)s(ESREVER=s(FII TCELES
"--

This requires an input table with a long strange name:

CREATE TABLE [MORF)0,1,)s(ESREVER=s(FII TCELES
] (s VARCHAR(999))

Note the return is included in the table name (not a recommended naming strategy for your databases, by the way).

Tables with otherwise invalid characters in their name need brackets or double-quotes around them, and the only way I could put the required quote at the beginning was to set it after a comment.

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

C# (.NET Core), 94

s=>Console.Write(s.SequenceEqual(s.Reverse()))//)))(esreveR.s(lauqEecneuqeS.s(etirW.elosnoC>=s

Improves slightly on the answer from Anderson Pimentel

Try it online

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

MUMPS, 36 bytes

r r r w r=$re(r) ; )r(er$=r w r r r

Explanation

There are no reserved keywords in MUMPS; the compiler just uses context to decide if you you are referencing a routine, command, or variable.

r : define routine "r"

r r : read input and assign to variable "r"

w r=$re(r) : write 1 if "r" equals its reverse ($re is the shortened form of $reverse)

; )r(er$=r w r r r : lame comment to make palindromic

Ungolfed version:

palindromeRoutine
 read input
 write input=$reverse(input)
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 11 bytes

.0(%=1=%(0.

Try it online!

Outputs via error. Throws an undefined method error if the input is a palindrome and a ZeroDivisionError otherwise.

\$\endgroup\$
1 2
3

Your Answer

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