Tuesday, April 15, 2008

Ruby: Determination of Palindrome


Share at Facebook

I'm providing a sample ruby function that can identify whether a given string or a number is palindrome or not. Remember, the provided function will work for both string and number.
## A simple function that takes string/number as parameter
## And return true/false depending upon palindrome nature
def palindrome(palindrom)
## Convert the given parameter into String first
## So that it can handle number too.
palindrom = String(palindrom);
x = 0;
y = palindrom.length - 1;
while(x <= y)
if(palindrom[x] != palindrom[y])
return false;
end
x = x + 1;
y = y - 1;
end
return true;
end

## Sample call of the function.
print palindrome("man"),"\n";
print palindrome(111),"\n";
If anyone requires to use case insensitive matching for palindrome, just use the upcase function from string class as below. This will make the string as upper class character string first, then try to match palindrome.
print palindrome("naN".upcase),"\n";
You can use built function to reverse the string first, then match equality of regular and reverse string. But this will be a bit slow.
def palindrome(palindrom)
palindrom = String(palindrom);
if(palindrom == palindrom.reverse)
return true;
end
return false;
end

print palindrome("n"),"\n";
print palindrome(111),"\n";
Thanks for reading the article.




No comments: