Palindrome detection: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎Recursive: Make it tail-recursive because I like it better that way)
No edit summary
Line 23: Line 23:
strip spaces.
strip spaces.


It might be useful for this task to know how to [[Reversing a string|reverse a string]].



=={{header|C}}==
=={{header|C}}==

Revision as of 20:24, 5 December 2008

Task
Palindrome detection
You are encouraged to solve this task according to the task description, using any language you may know.

Write at least one function/method (or whatever it is called in your preferred language) to check if a sequence of characters (or bytes) is a palindrome or not. The function must return a boolean value (or something that can be used as boolean value, like an integer).

It is not mandatory to write also an example code that uses the function, unless its usage could be not clear (e.g. the provided recursive C solution needs explanation on how to call the function).

It is not mandatory to handle properly encodings (see String length), i.e. it is admissible that the function does not recognize 'salàlas' as palindrome.

The function must not ignore spaces and punctuations.

An example of latin palindrome is the sentence "In girum imus nocte et consumimur igni", roughly translated as: we walk around in the night and we are burnt by the fire (of love). To do your test with it, you must make it all the same case and strip spaces.

It might be useful for this task to know how to reverse a string.

C

Non-recursive

This function compares the first char with the last, the second with the one previous the last, and so on. The first different pair it finds, return 0 (false); if all the pairs were equal, then return 1 (true). You only need to go up to (the length) / 2 because the second half just re-checks the same stuff as the first half; and if the length is odd, the middle doesn't need to be checked (so it's okay to do integer division by 2, which rounds down).

<c>#include <string.h>

int palindrome(const char *s) {

  int i,l;
  l = strlen(s);
  for(i=0; i<l/2; i++)
  {
    if ( s[i] != s[l-i-1] ) return 0; 
  }
  return 1;

}</c> More idiomatic version: <c>int palindrome(const char *s) {

  const char *t; /* t is a pointer that traverses backwards from the end */
  for (t = s; *t != '\0'; t++) ; t--; /* set t to point to last character */
  while (s < t)
  {
    if ( *s++ != *t-- ) return 0; 
  }
  return 1;

}</c>

Recursive

A single char is surely a palindrome; a string is a palindrome if first and last char are the same and the remaining string (the string starting from the second char and ending to the char preceding the last one) is itself a palindrome.

<c>int palindrome_r(const char *s, int b, int e) {

  if ( e <= 1 ) return 1;
  if ( s[b] != s[e-1] ) return 0;
  return palindrome_r(s, b+1, e-1);

}</c>

Testing

<c>#include <stdio.h>

  1. include <string.h>

/* testing */ int main() {

  const char *t = "ingirumimusnocteetconsumimurigni";
  const char *template = "sequence \"%s\" is%s palindrome\n";
  int l = strlen(t);
  
  printf(template,
         t, palindrome(t) ? "" : "n't");
  printf(template,
         t, palindrome_r(t, 0, l) ? "" : "n't");
  return 0;

}</c>

C++

The C solutions also work in C++, but C++ allows a simpler one: <cpp>

  1. include <string>
  2. include <algorithm>

bool is_palindrome(std::string const& s) {

 return std::equal(s.begin(), s.end(), s.rbegin());

} </cpp>

Haskell

Non-recursive

A string is a palindrome if reversing it we obtain the same string.

is_palindrome x = x == reverse x


Recursive

See the C palindrome_r code for an explanation of the concept used in this solution.

is_palindrome_r x | length x <= 1 = True
                  | head x == last x = is_palindrome_r . tail. init $ x
                  | otherwise = False

Java

Non-Recursive

<java>public static boolean pali(String testMe){ StringBuilder sb = new StringBuilder(testMe); return sb.toString().equals(sb.reverse().toString()); }</java>

Recursive

<java>public static boolean rPali(String testMe){ if(testMe.length()<=1){ return true; } if(testMe.charAt(0)!=testMe.charAt(testMe.length()-1)){ return false; } return rPali(testMe.substring(1, testMe.length()-1)); }</java>

MAXScript

Non-recursive

fn isPalindrome s =
(
    local reversed = ""
    for i in s.count to 1 by -1 do reversed += s[i]
    local reversed == s
)

Recursive

fn isPalindrome_r s =
(
    if s.count <= 1 then
    (
        true
    )
    else
    (
        if s[1] != s[s.count] then
        (
            return false
        )
        isPalindrome_r (substring s 2 (s.count-2))
    )
)

Testing

local p = "ingirumimusnocteetconsumimurigni"
format ("'%' is a palindrome? %\n") p (isPalindrome p)
format ("'%' is a palindrome? %\n") p (isPalindrome_r p)

Perl

Non-recursive

One solution (palindrome_c) is the same as the C non-recursive solution palindrome; while Perl palindrome sub uses the idea that a word is a palindrome if, once reverted, it looks the same as the original word (this is the definition of a palindrome).

<perl>sub palindrome {

 my $s = shift;
 return $s eq reverse $s;

}

sub palindrome_c {

 my $s = shift;
 for my $i (0 .. length($s) >> 1)
 {
    return 0 unless substr($s, $i, 1) eq substr($s, -1-$i, 1);
 }
 return 1;

}</perl>

Recursive

<perl>sub palindrome_r {

 my $s = shift;
 if (length $s <= 1) { return 1; }
 elsif (substr($s, 0, 1) ne substr($s, -1, 1)) { return 0; }
 else { return palindrome_r(substr($s, 1, -1)); }

}</perl>


Testing

<perl>sub mtest {

  my ( $t, $func ) = @_;
  printf("sequence \"%s\" is%s palindrome\n",
          $t, &$func($t) ? "" : "n't");

} mtest "ingirumimusnocteetconsumimurigni", \&palindrome; mtest "ingirumimusnocteetconsumimurigni", \&palindrome_r; mtest "ingirumimusnocteetconsumimurigni", \&palindrome_c;

exit;</perl>


Python

Non-recursive

This one uses the reversing the string technics (to revert a string Python can use the odd but right syntax string[::-1])

<python>def is_palindrome(s):

 return s == s[::-1]</python>

Recursive

<python>def is_palindrome_r(s):

 if len(s) <= 1:
   return True
 elif s[0] != s[-1]:
   return False
 else:
   return is_palindrome_r(s[1:-1])</python>

Testing

<python>p = "ingirumimusnocteetconsumimurigni" print "'" + p + "' is palindrome? ", is_palindrome(p) print "'" + p + "' is palindrome? ", is_palindrome_r(p)</python>

Ruby

Non-recursive

def is_palindrome(s)

 s == s.reverse

end

Recursive

def is_palindrome_r(s)

 if s.length <= 1
   true
 elsif s[0] != s[-1]
   false
 else
   is_palindrome_r(s[1..-2])
 end

end

Testing

p = "ingirumimusnocteetconsumimurigni" print "'" + p + "' is palindrome? ", is_palindrome(p), "\n" print "'" + p + "' is palindrome? ", is_palindrome_r(p), "\n"