Other sites

Palindrome String Detection by R

[This article was first published on R Analytics, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction. The famous palindrome – “able was i ere i saw elba” is attributed to Napoleon.

In some context, it would be an interesting problem to check whether a given string is “Palindrome” or not. The iterative solution ( through loop) would do, but, may be a few more lines of code. This problem would have a nice and easy solution through “Recursive” process or algorithm.” The problem would be broken in to a smaller problem, apply the same process until problem reaches to trivial level or “Base Case”. The base case for a string would a Null or Single Character.

Let us look at an example: “able was i ere i saw elba”, first we need to check whether first and last characters are equal or not, if yes, solution lies in finding whether “*ble was i ere i saw elb*” is a palindrome or not. The process goes on, until we reduce the problem to Null or Single Character. During the process if any iteration if the condition is not met , we can conclude that it is not a “Palindrome”.

User defined R Function is coded below:

First Function – “palindromecal” is a function which deals with recursive solution and 2nd function is a calling function which would be do some house keeping stuff before calling the recursive function.

Lastly any R discussion would be incomplete without a reference to the vectorization, this function can be used with other standard vector functions such as “lapply and sapply”.list.string list.new vec.new

# > vec.new# [1] FALSE TRUE TRUE FALSE

This piece may not have any use in any standard data analytics situations, but it can be concluded that R can be used for advanced text manipulations which is done by other languages such as Python, Perl, C or Java.