Thursday, October 14, 2010

Programming a Palindrome word

A palindrome word is a word that can be read the same way backwards (e.g. kayak, ana, redder, etc.). Well, for my programming class I was asked to prepare a code that reads a word and decides if it's a palindrome or not. It took me 3HRS to get it right, why? because I needed to implement recursion (it's a process in programming where a method calls itself until it meets a basic requirement that makes it stop). I must say I didn't like it, there is  lot of logic that goes into it. A LOT!!! like, what can make it stop? or what variables should modify the method? or why did my sister take my pain relievers from my bag?? YES! that's right she did... I KNOWWW, right?

so here, from meu to the world:
[if you don't get it skip 'til the closing words.]

public class Main {
    public static void main(String[] args) {
        String a = "kayak"; //WORD BEING READ

/*below a is the word, 0 is the position in the word where the method starts comparing this case "k", a.length()-1 is the last character of the word*/        
        if(checkPalindrome(a, 0, a.length()-1))
        System.out.println("Palindrome"); //Prints "Palindrome" is the method determines so

        else
            System.out.println ("Not!"); //Prints "Not!" if it doesn't
   }

  //method that checks word
    public static boolean checkPalindrome(String a, int s, int e){

        if (s>=e)
            return true;
        
        a = a.toLowerCase();//uppercase letters and lowercase letters have different numerical values that would return an error when comparing
        char b = a.charAt(s);//takes character at position s(0, 1, or 3, depends on word length)
        char c = a.charAt(e);//at position e

/*below if the chars in b and c match then position s is moved up one place and e down one, in the case of "kayak" after s reads the "k" position it would read "a" and e would be the same but from the end of the word towards the beginning*/
        if(b == c){
            s++;
            e--;
            return checkPalindrome(a, s, e);
        }

        else
            return false;
    }
}

okay, i hope you skipped my explanations because even I got tired by just writing them. the thing is that it works. WHAT'S NEXT? I'm trying to see how to make it work with a sentence but its kind of hard because of the spaces... 

LONG LIVE PRETTY THE PROGRAMMER! 
LOL << hahaha, it's a palindrome  O_0 


1 comment:

  1. i don't know what language your programming in, but in C you can use a stream and make it ignore spaces; so you can store a sentence to a variable and then stream into another variable to run the algorithm

    maybe you've tried that, good luck, its cool either way

    ReplyDelete