42
\$\begingroup\$

A palindrome is some string that is spelled the same way both backwards and forwards. For instance, 'Eva, can I stab bats in a cave?' is a palindrome (EVACANISTAB | BATSINACAVE)

For this code golf, using the language of your choice, determine if a given string is a palindrome or not.

Edge Cases:

  • Punctuation is not counted towards palindrominess.
  • Control characters are not counted towards palindrominess.
  • Whitespace is not counted towards palindrominess.
  • Numbers are counted towards palindrominess.
  • Case in this challenge is not counted towards palindrominess.
  • There is no limit to the length of strings to evaluate, except for what is imposed by your language of choice.
  • For this challenge, limit yourself to the ASCII character set.

Technical Requirements:

  • Only method bodies are needed; additional things like method signatures, data structure declarations, etc. do not count towards the victory requirement.
  • Code must compile or interpret without compile-time errors or exceptions.
  • Code must not throw any unhandled exceptions or crash. (Almost needless to say. Almost.)
  • Code must return some value indicating palindrominess. The data type depends on the language you use (e.g. a C# user might use a bool, whereas a JavaScript user could use a var.)
  • You may not write your own interpreter that performs this task as a 'native' capability so you can 'golf' a near-winning score. (Hopefully needless to say.)

Victory Condition:

  • The shortest code in characters wins.

Current Leader: tmartin (k, 25 characters)

...Want the magic green check mark by your answer? Beat this guy's answer!

\$\endgroup\$
  • 1
    \$\begingroup\$ Is I/O a part of the challenge, or a function body will do? \$\endgroup\$ – John Dvorak Apr 8 '13 at 18:43
  • 1
    \$\begingroup\$ The "breadcrumbs" for showing how the work is refined are available site-wide in all answers via revision history. There's no need to have a full history visible in the current version of the answer. \$\endgroup\$ – Peter Taylor Apr 8 '13 at 20:27
  • 1
    \$\begingroup\$ @WernerCD I'm sure the OP will change who gets the green tick when he comes back to check on the new responses. \$\endgroup\$ – Gareth Apr 9 '13 at 7:15
  • 2
    \$\begingroup\$ Not specifying a language really trivialises this challenge for me. As seen below, interpreted languages with a focus on high order text manipulation functions always get the shortest results. What is to stop me throwing together my own interpreter with a single function, ip(). My compete algorithm is now 'ip:i'. 4 characters. done. \$\endgroup\$ – Gusdor Apr 9 '13 at 8:11
  • 3
    \$\begingroup\$ @Gusdor see J and GolfScript suck all the enjoyment out of Code Golf and Language Handicap and related questions on this site's meta. \$\endgroup\$ – AakashM Apr 9 '13 at 8:25

43 Answers 43

1
\$\begingroup\$

Racket, 132 bytes

Pretty embarrassing, but maybe somebody can see a way of making this shorter!

((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)"")))

Code listing with test module

#lang racket

(define/contract (palindrome? s)
  (string? . -> . boolean?)
  ((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)""))))

(module+ test
  (require rackunit)
  (define tests
    '(("Eva, can I stab bats in a cave?" . #t)
      ("A man, a plan, a canal. Panama!" . #t)
      ("Madam, I'm Adam Corolla." . #f)
      ("757" . #t)
      ("Boeing 757" . #f)
      ("A man, a plan, a big shovel, a canal. Panama!" . #f)
      ("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__" . #t)))
  (for ([t tests])
    (check-equal? (palindrome? (car t)) (cdr t) (~a t))))
\$\endgroup\$
1
\$\begingroup\$

C++14, 104 bytes

Actually overlooked the requirement to ignore case and whitespace, so here is:

auto f=
[](auto s,int&n){
auto r=s.rbegin();n=1;for(auto c:s){if(isalnum(c)){while(!isalnum(*r))r++;if((c|32)!=(*(r++)|32))n=0;}}
}
;

strict solution, 72 68 bytes

-4 bytes for returning by parameter.

As unnamed lambda, assuming input s is of type std::string and returning the result by a parameter:

[](auto s,int&n){auto r=s.rbegin();n=1;for(auto c:s)if(c!=*r++)n=0;}

Ungolfed & usage:

#include <iostream>
#include <string>

auto f=
[](auto s, int& n){
  auto r=s.rbegin();
  n=1;
  for(auto c:s)
    if(c!=*r++)
      n=0;
}
;

int main(){
int n;
#define p(s) f(std::string(s),n); std::cout << n << std::endl
 p("Hello");
 p("ABCCBA");
 p("ABCBA");
}
\$\endgroup\$
1
\$\begingroup\$

Python(python 2.7.6), 79 chars

"Sorry I don't get what characters to count so I wrote the whole program"

import re
n=raw_input()
n=re.sub("[^a-z]+","",n.lower())
print n==n[::-1]

This will print True if input string is palindrome else False.

Code_link:http://ideone.com/b4NzLD

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! It is stated in the languages specs that "Punctuation is not counted towards palindrominess" and I don't think this submission takes care of that. Unfortunately, that makes this answer invalid, but you can fix it right now \$\endgroup\$ – Cows quack Mar 31 '17 at 18:12
1
\$\begingroup\$

REXX, 84 bytes

arg n
n=space(translate(n,,translate(n,,xrange(a,z)xrange(0,9))),0)
say n=reverse(n)

arg n reads argument into variable n, converting it to upper-case.

xrange(a,z)xrange(0,9) concatenates the two ranges A—Z and 0—9.

translate takes a string to process, an output translation table and an input translation table, and optionally a padding character to replace those characters not found in the output table with. Hence translate(n,,xrange(a,z)xrange(0,9)) maps the string n with an input table consisting only of alphanumerical characters and an empty output table, resulting in a string consisting only of punctuation, spaces and other non-alphanumericals (since they were not in either table). The filtered-out characters are rendered as spaces.

translate(n,,translate(n,,xrange(a,z)xrange(0,9))) uses the above non-alphanumerics string as an input table and an empty output table, applying it to n, resulting in a string consisting only of alphanumericals, since they were not in the input or output tables. The non-alphanumerics are rendered as spaces.

space() takes a string and a number, spacing out the words with the supplied amount of spaces between. In this case, the supplied number is 0, hence all spaces are removed.

By this point, n has been reduced to consisting only of alphanumeric characters without any spaces.

say n=reverse(n) prints out whether n is identical to its reversed version.

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

APL, 78 65 Bytes

l←⎕D,⎕UCS v+32⊣c←⎕D,⎕UCS v←64+⍳26⋄(⌽≡⊢)∊{⍵/⍨⍵∊l}¨{⍵∊c:l[c⍳⍵]⋄⍵}¨⎕

I'm going to assume that the Original Poster meant limit the INPUT string to the Ascii character set.

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

Dyalog APL (18 characters)

 {⍵≡⌽⍵}'\w'⎕S'\u0'⊢

Search for alphanumeric characters in the right argument, and return any found upper-cased (this avoids any need for punctuation, whitespace and casing). Then just check what's returned to see if it matches the reverse.

Example

{⍵≡⌽⍵}'\w'⎕S'\u0'⊢'Eva, can I stab bats in a cave?'
    1
\$\endgroup\$
  • \$\begingroup\$ This is a snippet. The (tacit) function is {⍵≡⌽⍵}'\w'⎕S'\u0' which can be named (or parenthesised) before application. Also, you can save another byte by replacing {⍵≡⌽⍵} with (⊢≡⌽). \$\endgroup\$ – Adám Oct 25 '17 at 16:28
0
\$\begingroup\$

JavaScript Code :: ONLY 140 characters Palindrome

function palindrome()
{
    var user=prompt("Enter the characters to check the palindrome");
    var split=user.split('').reverse().join(''); // ONLY this line counts 
    if(user == split)
    {
        alert("The given word is a Palindrome");
    } else
    {
        alert("The given word is not a Palindrome");
    }

}

palindrome();

\$\endgroup\$
  • 3
    \$\begingroup\$ Erm...afraid not, the comparison is also part of checking that a string is a palindrome. \$\endgroup\$ – Gareth Apr 9 '13 at 7:14
  • \$\begingroup\$ oh... Sorry.. Then its takes 140 characters.. \$\endgroup\$ – Praveen Apr 9 '13 at 7:16
  • 7
    \$\begingroup\$ The requirement says you need to ignore uppercase vs. lowercase differences and punctuation. \$\endgroup\$ – manatwork Apr 9 '13 at 7:21
  • \$\begingroup\$ Additionally, don't worry about the method signature. We're just worried with how you solve the problem, not language-specific boilerplate. \$\endgroup\$ – Andrew Gray Apr 9 '13 at 13:15
0
\$\begingroup\$

Racket 118 bytes

(let((l(filter(λ(x)(or(char-alphabetic? x)(char-numeric? x)))(string->list(string-upcase s)))))(equal? l(reverse l)))

Ungolfed:

(define (palindrome? s)
  (let((l(filter(λ(x)(or(char-alphabetic? x)
                        (char-numeric? x)))
                (string->list (string-upcase s)))))
    (equal? l(reverse l))))

Testing:

(palindrome? "abc  dcB;_A")
(palindrome? "abc;@#$zdc b  a")
(palindrome? "1%^&234 56")
(palindrome? "1a234 * ^ && 565432A1")

Output:

#t
#f
#f
#t
\$\endgroup\$
  • \$\begingroup\$ This is neither case insensitive and nor does it ignore punctuation, control characters and whitespace. \$\endgroup\$ – Titus Apr 4 '17 at 23:51
  • \$\begingroup\$ Thanks for pointing out. I have corrected the code above. \$\endgroup\$ – rnso Apr 5 '17 at 2:02
0
\$\begingroup\$

AHK, 83 bytes (L7 loser)

StringUpper,s,1
s:=RegExReplace(s,"[\W_]")
Loop,Parse,s
t:=A_LoopField t
Send % s=t

Outputs 1 for palindromes and 0 for not.

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

C, 199 bytes

#define R return
#define C unsigned char
#define F for
s(C*a){C*b;if(a&&*a)F(b=a+strlen(a)-1;;++a,--b){F(;a<b&&!isalnum(*a);)++a;F(;a<b&&!isalnum(*b);)--b;if(a>=b)R 1;if((*a|32)-(*b|32))R 0;}R 1;}

//ungolf

v(C*a)
{ C*b;
 if(a&&*a)
   F(b=a+strlen(a)-1;;++a,--b)
           {F(;a<b&&!isalnum(*a);)++a;
            F(;a<b&&!isalnum(*b);)--b;
            if(a>=b)           R 1;
            if((*a|32)-(*b|32))R 0;
           }
 R 1;
}

#define P printf
main()
{C*b="Eva, can I stab bats in a cave?";
 P("%s %d\n", b, s(b));
 R 0;
}

//results

//Eva, can I stab bats in a cave? 1
\$\endgroup\$
0
\$\begingroup\$

Retina, 31 bytes (non-competing)

\W

T`l`L
+`^(.)(.*)\1$
$2
^.?$

Try it online!

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

Common Lisp, 72 65 bytes

(let((y(remove-if-not'alphanumericp(read))))(equalp(reverse y)y))

-7 bytes thanks to @ceilingcat !

Try it online!

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

QuadS, 19 bytes

Equivalent to James Heslip's solution.

⍵≡⌽⍵
\w
\u&

Try it online!

Is…

⍵≡⌽⍵ the text identical to its reverse

\w after finding all word characters

\u& and uppercasing them

?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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