Palindrome

I need a program fitting these rules:
-This program must be named Palindrome.
-Function adjust - This function will be passed the original string from main. This function will be passed the original string from main. This function will traverse the string in order and pull each character. If this character is a letter, it will add this letter to the new string. If it is not a letter, the character will be ignored and will move on to the next letter. The adjusted string will be passed back to main. (Basically removing all blank spaces and all punctuation marks from the original string.)
-Function reverse - This function will be passed the adjusted string from main. First, it makes sure that all the characters of the string are in lowercase. Second, it traverses the string and pulls each character in reverse order. It will add the letter to a new string. This string will be returned to main. (Remember that this reverses the string that does not have any spaces or punctuation marks.)
-Function match - This function will be passed the adjusted string and the reversed string. It will perform the task of checking to see if the strings are the same. The function will return either true or false to the main.
-Main - This will test our program and check both a palindrome string and a non-palindrome string. Be sure that you include enough variables for all items that are to be used and to hold all answers that are returned from other functions.
( This program will only have input in the code not in the cmd prompt, the sentence that should work is Madam, I'm Adam!, the one that should work is This should fail!, make sure it prints if it is a palindrome or not. Any help would be greatly appreciated please try to keep it lower level so i can understand it,)

As specified, this program will never work.
The spec for the reverse function says: "First, it makes sure that all the characters of the string are in lowercase". Which, quite apart from being bad design (nothing in the method name tells us the string is going to be down shifted) leaves a potentialy mixed case string being compared with a lower case one.
To fix this, downshift in the adjust method (not quite such bad design as the name is so vague that you can justifiably do whatever you like in it).
Enjoy!
public class Astrads1
     static String adjust(String source)
          String adjusted= "";
          for (int i= 0; i< source.length(); i++) {
               if (Character.isLetter(source.charAt(i)))
                    adjusted += source.charAt(i);
          return adjusted.toLowerCase();
     static String reverse(String source)
          String reversed= "";
          for (int i= source.length()-1; i >= 0; i--)
               reversed += source.charAt(i);
          return reversed;
     static boolean match(String adjusted, String reversed)
          for (int i= 0; i< adjusted.length(); i++) {
               if (adjusted.charAt(i) != reversed.charAt(i))
                    return false;
          return true;
     public static void main(String[] argv)
          String[] sources= new String[] {
               "Madam, I'm Adam!", "This should fail!" };
          for (int i= 0; i< sources.length; i++) {
               String source= sources;
               String adjusted= adjust(source);
               String reversed= reverse(adjusted);
               boolean matches= match(adjusted, reversed);
               System.err.println(
                    "Source= " source
                    "\nAdjusted= " adjusted
                    "\nReversed= " reversed
                    "\nMatches= " +matches);
               System.out.println(
                    "'" source "' is" +(matches ? "" : " not") +" a palindome");

Similar Messages

  • Checking for Palindrome, is there a better way?

    Hi all,
    i m pasting the code which checks whether its a Palindrome or not. I am sure someone here could come up with some better way. I'll be obliged if they point out the changes.
    //Class PalindromeBeta
    public class PalindromeBeta{
         private static String s;
         public PalindromeBeta(){
         public static boolean isPalindrome(String as){
              s= as;
              int string_length = s.length();
              int stop_index = (int)(string_length/2);
              int start_index = 0;
              int end_index = string_length;
              int second_index = 1;
              if (string_length == 1)
              return false;
              else{
                   do{
                        if(s.substring(start_index,second_index).equalsIgnoreCase(s.substring((end_index-1), end_index))){
                             start_index++;
                             end_index--;
                             second_index++;
                        else
                        return false;
                   while(start_index != stop_index);
                   return true;
    //Class P7_16 with the main() method     
    public class P7_16beta{
         public static void main(String[] args){
              ConsoleReader console = new ConsoleReader(System.in);
              PalindromeBeta pd = new PalindromeBeta();
              boolean done = false;
              do{
                   System.out.println("Enter a String(Q to quit)");
                   String input = console.readLine();
                   if (input.equalsIgnoreCase("Q"))
                   done = true;
                   else if(pd.isPalindrome(input) == true)
                   System.out.println("It is a Palindrome");
                   else
                   System.out.println("It is not a Palindrome");
              while (done == false);
    //Class ConsoleReader , a hepling class for reading input
    import java.io.*;
    public class ConsoleReader
         private BufferedReader reader;
         public ConsoleReader(InputStream instream)
         reader = new BufferedReader(new InputStreamReader(instream));
    public String readLine()
    String inputLine ="";
    try
              inputLine = reader.readLine();
    catch(IOException e)
    System.out.println(e);
    System.exit(1);
    return inputLine;
    public int readInt()
         String inputString = readLine();
    int n = Integer.parseInt(inputString);
    return n;
    public double readDouble()
         String inputString = readLine();
    double x = Double.parseDouble(inputString);
    return x;
                        

    I'm posting my little code here: It compares every character in the string. It's not the faster way, but I think it's still very reliable.
    import java.io.*;
    class palindromo {
         public static void main (String [] args) throws Exception {
              String test = args[0];
              boolean result = true;
              if (test.length() <= 1)
                   result = false;
              else {
                   int end, begin;
                   begin = 0;
                   end = test.length() - 1;
                   if ((test.length())%2 == 0) {
                        while (begin < end) {
                             if (test.charAt(begin) != test.charAt(end)) {
                                  result = false;
                                  break;
                             begin++;
                             end--;
                   else {
                        int medio = (test.length() ) / 2 + 1;
                        while (begin < medio && end > medio) {
                             if (test.charAt(begin) != test.charAt(end)) {
                                  result = false;
                                  break;
                             begin++;
                             end--;
              System.out.println("The fact that the string is a palindrome is " + result);
         

  • Making a program to detect a palindrome

    For my class I have to make a program that will detect whether or not a word is a palindrome. Here's what I have right now:
    import java.io.*;*
    *import java.util.*;
    public class Tester
            public static void main(String args[])
                     Scanner f = new Scanner(System.in);
                     System.out.print("Enter a word. ");
                     String word = f.nextLine();
                     char reverse=0, pali=0;                
                     int j, r;
                     for(j = word.length()-1; j>=0; j--)
                        reverse = word.charAt(j);      //To print the string backwards
                        for(r = 0; r <= word.length()-1; r++)
                            pali = word.charAt(r);     //Printing the string normally                     
                            if(pali!=reverse) 
                                System.out.println(word + " is not a palindrome.");
                                break;
                            else if(pali == reverse)
                            System.out.println(word + " is a palindrome.");                       
    }So basically what I'm trying to do there is to have one loop print each character backwards and a loop inside of that print each character forwards, and inside of the second loop I check to see whether the characters are identical, and if they are not, the word isn't a palindrome. It makes sense to me, but the output looks like this, using racecar as an example:
    Enter a word. racecar
    racecar is a palindrome.
    racecar is not a palindrome.
    racecar is not a palindrome.
    racecar is not a palindrome.
    racecar is not a palindrome.
    racecar is not a palindrome.
    racecar is not a palindrome.
    racecar is a palindrome.
    racecar is not a palindrome.I understand why it prints that many times, because it's still iterating inside the first loop, but I have no idea how break the first loop. Also, clearly, it just doesn't work... any tips?
    All help is greatly appreciated.

    Thanks for the reply.
    I'm not sure if I got exactly what you meant, but here's how I understood it:
    import java.io.*;
    import java.util.*;
    public class Palindrome
            public static void main(String args[])
                     Scanner f = new Scanner(System.in);
                     System.out.print("Enter a word. ");
                     String word = f.nextLine();
                     boolean b = true;
                     char pali = 0, reverse = 0;
                     int j, r;
                     j = word.length()-1;
                     r = 0;
                     while(j!=r)
                            pali = word.charAt(r);
                            reverse = word.charAt(j);
                            if(pali!=reverse)
                                        b = false;
                                        break;
                            else
                                    b = true;
                                    r++;
                                    j--;
                 if(b)
                 System.out.println(word + " is a palindrome.");
                 else
                 System.out.println(word + " is not a palindrome.");
        }I made a mistake somewhere, because when I input a palindrome it might say that it is a palindrome(more than once for some reason), but if I input a non-palindrome it doesn't respond at all. No idea why, because I have an "else" statement that should make it do so...
    So where did I go wrong?

  • Please give me a program to display a palindrome.

    PROGRAM FOR PALINDROME AND IF WE GIVE N = 3 O/P SHOULD BE LIKE :
    Edited by: Vijay  Kumar on Jul 15, 2008 2:44 PM

    PARAMETER P_STRING(15) TYPE C.
    DATA:W_A(1) TYPE C,
         W_A1(1) TYPE C,
         W_B TYPE I,
         W_C TYPE I VALUE 1,
         W_D TYPE I,
         W_X TYPE I,
         W_F TYPE I VALUE 0,
         W_E TYPE I VALUE 1.
    W_B = STRLEN( P_STRING ).
    W_D = W_B - 1.
         DO W_B TIMES.
         MOVE P_STRING+W_D(W_C) TO W_A.
         MOVE P_STRING+W_F(W_E) TO W_A1.
         IF W_A = W_A1.
         ADD 1 TO W_X.
         ENDIF.
         W_D = W_D - 1.
         W_F = W_F + 1.
         ENDDO.
         IF W_X = W_B.
         WRITE TEXT-111.
         ELSE.
         WRITE TEXT-100.
         ENDIF.

  • Palindrome function

    Hi,
    Do we have a function in Oracle10G to check in stored procedure the input we send is a palindrome or not..
    say eg.. Malayalam is a Palindrome
    Thanks,
    Dinesh Jaganathan

    Tom Kyte:
    "Note REVERSE is an undocumented function and, as such, should be used
    carefully. I do not recommend using REVERSE in “real” code, as its undocumented
    nature implies that it is not supported."
    in the link -
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:2424495760219
    which make us use the utl_raw api:
    create or replace function f_is_palindrome(p_str varchar2) return number is
    begin
    return
             case
                     when upper(p_str) = UTL_RAW.cast_to_varchar2( UTL_RAW.REVERSE ( UTL_RAW.cast_to_raw(upper(p_str)))) then
                                      1
            else      
                                      0
            end; 
    end f_is_palindrome;
    SQL> select f_is_palindrome('Malayalam') from dual;
    F_IS_PALINDROME('MALAYALAM')
                               1
    SQL> select f_is_palindrome('Hello') from dual;
    F_IS_PALINDROME('HELLO')
                           0Amiel
    Message was edited by:
    Amiel D.

  • Java Code Help-Palindromes

    Sorry to trouble anyone, but I need help with coding a program dealing with Palindromes. I have some of the code already down, but I'm having trouble having the program recognize certain words as Palindromes (e.g. Racecar, madam, etc.). Note that this program is also case-sensitive. So I was just wondering if anyone had any code that could fix this maybe? If you do, it'd be appreciated. Thanks

    public static void main(String[] args)
              String strPalin = null;
              if(args[0] != null)
                   strPalin = args[0];
              byte[] b = strPalin.getBytes();
              int strlen = b.length;
              int i = (strlen - 1);
              int j = 0;
              byte[] c = new byte[strlen];
              while(i>-1)
                   c[j] = b;
                   i--;
                   j++;
              String strrev = new String(c);
              if(strrev.equals(strPalin))
                   System.out.println("Oops its a Palindrome:" +strPalin);
              }else{
                   System.out.println("its not a Palindrome: " +strPalin);
    hi,
    plz check it out , it may serve ur requirement i think .
    keep mail to [email protected]

  • Why is the word palindrome not a palindrome?

    Why is the word palindrome not a palindrome?

    That's why : ( with thanks to Demetri Martin Link: [http://www.pastemagazine.com/articles/2009/02/demetri-martins-palindrome-poem.html] )
    Dammit Iu2019m mad.
    Evil is a deed as I live.
    God, am I reviled? I rise, my bed on a sun, I melt.
    To be not one man emanating is sad. I piss.
    Alas, it is so late. Who stops to help?
    Man, it is hot. Iu2019m in it. I tell.
    I am not a devil. I level u201CMad Dogu201D.
    Ah, say burning is, as a deified gulp,
    In my halo of a mired rum tin.
    I erase many men. Oh, to be man, a sin.
    Is evil in a clam? In a trap?
    No. It is open. On it I was stuck.
    Rats peed on hope. Elsewhere dips a web.
    Be still if I fill its ebb.
    Ew, a spideru2026 eh?
    We sleep. Oh no!
    Deep, stark cuts saw it in one position.
    Part animal, can I live? Sin is a name.
    Both, oneu2026 my names are in it.
    Murder? Iu2019m a fool.
    A hymn I plug, deified as a sign in ruby ash,
    A Goddam level I lived at.
    On mail let it in. Iu2019m it.
    Oh, sit in ample hot spots. Oh wet!
    A loss it is alas (sip). Iu2019d assign it a name.
    Name not one bottle minus an ode by me:
    u201CSir, I deliver. Iu2019m a dogu201D
    Evil is a deed as I live.
    Dammit Iu2019m mad.
    Regards,
    Dirk.

  • Please help me on this palindrome program

    import java.io.*;
    public class lab16b2
    public static void main (String args[]) throws IOException
              BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
              boolean finished = false;
              clearScreen(31);
              do
                   System.out.print("Enter a string  ===>>  ");
                   Palindrome p = new Palindrome(input.readLine());       
                   p.displayData();
                   System.out.print("\nDo you wish to repeat this program [Y/N]?  ===>>  ");
                   String repeat=input.readLine();
                    boolean right=(repeat.equals("Y") || repeat.equals("yes")||repeat.equals("y")||repeat.equals("YES"));
                    if (right)
                      System.out.println();
                   else
                   System.out.println();
                      finished = true;
              while (!finished);
         public static void clearScreen(int numberoflines)
                for(int i=0;i<numberoflines;i++)
                     System.out.println();
    class Palindrome
       private String s1;          // stores original string entered at the keyboard
       private String s2;          // stores s1 with punctuation and spaces removed
       private boolean palindrome;
       private boolean almostPalindrome;
       private boolean isPal(String s)
            System.out.println("String:" + s1);
       s2=s1.toLowerCase();               
       int a=0;
        int b=s2.length()-1;
        while (a<b)
          if(s2.charAt(a) != s2.charAt(b))
            return false;
          a++;
          b--;
        return true;           
       private boolean isAlmostPal()
            s2=s1.toLowerCase();
       s2=s2.replaceAll("[^a-zA-Z0-9]+", "");     
        int a=0;
        int b=s2.length()-1;
        while (a<b)
          if(s2.charAt(a) != s2.charAt(b))
            return false;
          a++;
          b--;
       return true;
       public void checkData()
           if(isPal(s1)==true)
                almostPalindrome=false;
           else
         almostPalindrome=true;
       public Palindrome(String s)
            s1=s;
            s2="";
       public void displayData()
             if (isPal(s2))
          System.out.println("Palindrome: true");
        else
          System.out.println("Palindrome: false");
        if(isAlmostPal())
          System.out.println("Almost Palindrome: true");
        else
          System.out.println("Almost Palindrome: false");
    The output is supposed to be:
    Enter a string ===>> Racecar
    String: Racecar
    Palindrome: true
    Almost Palindrome: false
    Do you wish to repeat this program [Y/N]? ===>> y
    Enter a string ===>> Aardvark
    String: Aardvark
    Palindrome: false
    Almost Palindrome: false
    Do you wish to repeat this program [Y/N]? ===>> y
    Enter a string ===>> A man, a plan, a canal, Panama
    String: A man, a plan, a canal, Panama
    Palindrome: false
    Almost Palindrome: true
    Do you wish to repeat this program [Y/N]? ===>> n
    While on the other hand, my output is:
    Enter a string ===>> Racecar
    String: Racecar
    Palindrome: true
    Almost Palindrome: true<--SUPPOSED TO BE FALSE
    Do you wish to repeat this program [Y/N]? ===>> y
    Enter a string ===>> Aardvark
    String: Aardvark
    Palindrome: false
    Almost Palindrome: false
    Do you wish to repeat this program [Y/N]? ===>> y
    Enter a string ===>> A man, a plan, a canal, Panama
    String: A man, a plan, a canal, Panama
    Palindrome: false
    Almost Palindrome: true
    Do you wish to repeat this program [Y/N]? ===>> n
    I don't know how to change it without altering the other palindromes. Help will be greatly appreciated!

    Try this:
    import java.io.*;
    public class lab16b2 {
       public static void main (String args[]) throws IOException {  
          BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
          boolean finished = false;
          clearScreen(31);
          boolean right;
          do {
             System.out.print("Enter a string  ===>>  ");
             Palindrome p = new Palindrome(input.readLine());       
             p.displayData();
             System.out.print("\nDo you wish to repeat this program [Y/N]?  ===>>  ");
             String repeat = input.readLine();
             right = (repeat.equals("Y") || repeat.equals("yes")
                   ||repeat.equals("y")||repeat.equals("YES"));
             System.out.println();
          } while(right);
       public static void clearScreen(int num) {
          for(int i=0; i < num; i++) System.out.println();
    class Palindrome {
       private String data;
       public Palindrome(String s) {
              data = s;
          /** Returns true iff s is a palindrome. */
       private static boolean isPal(String s) {
          int a = 0;
          int b = s.length() - 1;
          while(a < b) {
             if(s.charAt(a) != s.charAt(b)) return false;
             a++;
             b--;
          return true;           
       public boolean isPalindrome() {
            return isPal(data.toLowerCase());
       public boolean isAlmostPal() {
          String toTest = data.toLowerCase().replaceAll("[^a-zA-Z0-9]+", "");
          return !isPalindrome() && isPal(toTest);
       public void displayData() {
          System.out.println("Palindrome: " + isPalindrome());
          System.out.println("Almost Palindrome: " + isAlmostPal());
    }

  • A Palindrome problem

    i know how to solve the palindrome problem when the user inputs a string value, already solved that one, but now i'm having problems solving for when the user inputs an integer
    my assigment calls for getDigits, which takes an integer as a parameter and returns an integer array containing the digits of the number.
    i've got that finished
    now i need to create a separate static method, call it isPalindrome, that will take an integer array as a parameter and return a boolean value of true or false indicating whether the integers in the array form a number palindrome.
    so far this is what i have...
    import java.util.*;
    public class Palindrome
         public static void main(String[] args)
              Scanner kbd = new Scanner(System.in);
              int choice;
              do
                   System.out.println("Enter a number to check if it's a palindrome:");
                   choice = kbd.nextInt();
                   getDigits(choice);
              }while (choice > 0);
         private static int[] getDigits(int num)
              if (num <= 0)
                   System.out.println("Bad input in getDigits. Goodbye!");
                   System.exit(1);
              int count=1;
              int num2 = num/10;
              while (num2 > 0)
                   count++;
                   num2 = num2/10;
              int[] tmp = new int[count];
              for (int i = tmp.length-1; i>=0; i--)
                   tmp[i] = num%10;
                   num = num/10;
              return tmp;
    private static boolean isPalindrome(int[] tmp2)
              int length = num; //how do i find the length of the tmp array?
              for (int j = 0; j < length; j++)
                   tmp2[j] = tmp[length - 1 - j];
    }

    ohh gotcha goctha
    thank you sooo much for the help, i really appreciate it! just fixed my isPalindrome method
    now i just have one last thing to figure out...
    Pal is not being read locally... yet i use it just a few lines after i initiate it... which causes everything to be returned as positive
    import java.util.*;
    public class Palindrome
         public static void main(String[] args)
              Scanner kbd = new Scanner(System.in);
              int choice;
              do
                   System.out.println("Enter a number to check if it's a palindrome:");
                   choice = kbd.nextInt();
                   int[] digitsArr = getDigits(choice);     
                   boolean Pal = isPalindrome(digitsArr);
                   if (Pal = true)
                        System.out.println(choice + " is a palindrome!");     
                   if (Pal = false)
                        System.out.println(choice + " is NOT a palindrome");
              }while (choice > 0);
         private static int[] getDigits(int num)
              if (num <= 0)
                   System.out.println("Bad input in getDigits. Goodbye!");
                   System.exit(1);
              int count=1;
              int num2 = num/10;
              while (num2 > 0)
                   count++;
                   num2 = num2/10;
              int[] tmp = new int[count];
              for (int i = tmp.length-1; i>=0; i--)
                   tmp[i] = num%10;
                   num = num/10;
              return tmp;     
         private static boolean isPalindrome(int[] toCheck)
              int len = toCheck.length;
              for (int j = 0; j < len ; j++)
                   if(toCheck[j] != toCheck[len - 1 - j])
                        return false;
              return true;
    }

  • Palindrome 1 error

    I am new to the java scene. I had an error occur and was hoping for some help. thanks in advance
    Error 1:
    palindromeb.java:13: cannot resolve symbol
    symbol : variable Input
    location: class Palindrome
    number = Input.readInt("Enter a 5 digit number:");
    ^
    source code
    public class Palindrome{
    public static void main(String [] args) {
    //declare the variables
    int number, digit1, digit2, digit3, digit4, digit5;
    //get the number
    System.out.println();
    do
    number = Input.readInt("Enter an 5 digit number:");
    while ((number < 10000) || (number > 99999));
    //get the digits
    digit1 = number % 10;
    number = (number - digit1) /10;
    digit2 = number % 10;
    number = (number - digit2) /10;
    digit3 = number % 10;
    number = (number - digit3) /10;
    digit4 = number % 10;
    number = (number - digit4) /10;
    digit5 = number % 10;
    if ((digit1 == digit5) && (digit2 == digit4))
    System.out.println("Palindrome!");
    else
    System.out.println("Not a palindrome!");
    System.out.println();

    Another thing you might want to look at to get use information is Swing classes, mainly JOptionInputDialog.(I think that's the name. If not, someone correct me!) Anyway, you can pop up a box to have a user enter a value. Now, this automatically returns a String, so you need to cast it to an integer to use it correctly.
    readNumber=JOptionInputDialog("Enter a number");
    newNumber=Integer.parseInt(readNumber);
    I think the syntax on that is correct, if not close. If not, I'm sure I will be corrected, but there's the general idea. You do need to import javax.swing.*; in order to use the Input Dialog Box. Again, if my syntax is off, someone please correct me, but I'm sure this is a possible answer...

  • Finding Longest Palindrome Given a File

    Hello Everyone,
    I am tackling an algorithmic problem trying to find the longest palindrome inside of a text file. As of right now, I know how to determine if a word is or is not a palindrome. However, the issue that I am having at the moment is trying to come up with an efficient algorithm that can solve this in the fastest way possible. Please help give ideas/suggestions on an algorithm that I should follow to achieve this.
    So for example, lets say we have a text file that has 10,000 characters. One of the things that I have concluded is that in order to determine if a word is a palindrome, you must be able to know the first and last characters. Right now, the only thing that I can think of is to:
    for( start with the first character x,  until the last character 10,0000)
              int Y = index 10,000
              while( X < Y )
                    if(the substring from X to the last character Y is not a palindrome)
                    Y = Y - 1;
                    else
                             currentLongestPalindrome = substring from X to Y;
                             BREAK;
    }Sorry everyone for the incorrect Java syntax, but that is the basic idea that I have come up with. This looks terrible as it is taking over an hour to be able to run this solution. Do you guys have any suggestions?
    Thanks in advance.

    Hi,
    I don't think you got the point of my main suggestion.
    Just check each three letter sequence until you find what may be the centre of a palindrome then and only then expand your check
    For your example
    "DSAFJKLSAFDJDASFLJASDFLASJFKSJHCNXVABCDDCBAMXBCXBZNZQOEIQEWOUWQOUWQEPQWUE"
    DSA
    SAF
    AFJ
    etc
    e.g.
    DSA = FALSE
    SAF = FALSE
    FDJ = FALSE
    DJD = TRUE -> F*DJD*A = FALSE - Current longest = 3
    JDA = FALSE
    DAS = FALSE
    CDD = POSSIBLE -> CDDC = TRUE -> BCDDCB = TRUE -> ABCDDCBA = TRUE -> VABCDDCBAM = FALSE - Current longest = 8
    DDC = POSSIBLE (no need to check less than 8) -> ABC*DDC*BA = TRUE -> VABCDDCBAM = FALSE - Current longest still 8
    DCB = FALSE
    etc
    That sequence consists of 40 checks of three letter sequences and only needs to expand on 3 of them.
    So on a 10,000 char file you would perform a max of 9,998 initial checks and then only expand on those that require it.
    In an amendment to my initial suggestion sequence 'aaa' could also be the centre of a palindrome.
    Hope this is clearer
    Eric

  • Yet another, more difficult palindrome problem

    Hi guys,
    I also have a Palindrome problem! For this problem, we are given a string and we have to print out all the possible palindromes of all the subsets of this string, in order.
    For example, given "ab", the set of subsets would be {a, ab, b, ba} and we'd have to print out:
    a
    aa
    aba
    abba
    b
    baab
    bab
    bb
    Each substring has 2 palindromes (i.e. abc has palindromes abcba and abccba).
    I know we can easily generate all the substrings and all the palindromes and then just sort it. However, for a string of 8 characters, we're required to print out all the palindromes in 3.2 seconds! (If the 8 characters are unique, that's over 200,000 lines!).
    Any ideas on how to go about this? Is there an elegant recursive solution for this? Would using an ArrayList slow down my program? Is there a faster way to print things?
    Thanks a bunch!!!

    Hi,
    I've actually finished writing it. I've been trying
    to speed it up for 2 days now. I've managed to tweak
    it from 13 seconds to 7 seconds, but it's still too
    slow (i need it to be faster than 3.2 seconds).
    Thanks!Who are you? Are you val018?
    I have to be a bit stupid, but I don't understand the rules. You say:
    given "ab", the set of subsets would be {a, ab, b, ba} O, that I understand, and then you show the example output.
    a
    aa <-- How do you construct this from the subsets shown?
    aba
    abba
    b
    baab
    bab
    bbThat is. Are you allowed to use the same subset more than once? In that case you have an infinitive result set:
    a
    aa
    aaa
    aaaa
    etc..
    /Kaj

  • Help with numerical palindrome!!!

    im supposed to write a prog that reads in a positive integer, and if its a numerical palindrome, correct will be printed. otherwise, wrong will be printed. however, i cant use array and string methods. how else?
    to note: numerical palindrome = a no. whose digits read the same forward and backward...for eg. 14741 => true but 14721 => false
    help appreciated!!

    geeez...cant compile the followinggg...why????     
    public static void main(String[] args)
              int input,digit;
              boolean output;
              Scanner new = sc Scanner(System.in);
              System.out.println("Enter integer number: ");
              digit=sc.nextInt();
              while (input!=-1)
    int n=0,newNum=0;
    digit = countDigit(input);                                   //method to calculate number of digits for variable input
    n = input;
    while(n>0)
    newNum += n%10*Math.pow(10,digit-1);
    n/=10;
    digit--;
    if (newNum == input)
    output = true;
    else
    output = false ;
    System.out.println("Output:" +output);
    System.out.print("\nEnter integer number:");
    input = sc.nextInt();
    System.out.println("<Program terminates>");
    public static int countDigit(int n)
    int numDigit=0;
    while(n>0)
    n/=10;
    numDigit++;
    return numDigit;     
    }

  • Palindrome Test with Recursive Method

    I was assigned in class to do make a program containing a recursive method that tests if the user's input is a palindrome. My instructor helped us out by giving us some lines of code for us to complete, however rather than helping me, they've only confused me...
    package project6;
    public class Palindrome {
    void main(String[] args) {
            // TODO code application logic here
            char charArray[] = args[0].toCharArray();
        public static Boolean testPalindrome(char[] text, int beg, int end) {
            //First case: the fragment in question is empty
            //This will be the case if beg is > end
            if(beg > end)
                return true;
            //Second case: the fragment contains just one character
            //This will be the case when beg == end.
            if(beg == end)
                return true;
            //Third case: is it of the form "x" + s + "x"
            if(testPalindrome(??, ?, ?))
            else
            return false;
    }Firstly,
            if(beg > end)
                return true;How does this statement check if the array is empty? And why use >? Shouldn't it be == ?
    Secondly,
            if(beg == end)
                return true;I understand this it to test if there is only 1 character, but don't palindromes with more than 1 character have the same beg and end? So why do this test?
    Thirdly,
    I don't get why a recursive function is necessary. Wouldn't it be much easier to store the input text into 2 arrays one in its original form and reversed form, and compare the two if they are identical?
    I would do that, but he wants our class to follow his way ...

    onguy3n wrote:
    I don't get why a recursive function is necessary. Wouldn't it be much easier to store the input text into 2 arrays one in its original form and reversed form, and compare the two if they are identical?
    I would do that, but he wants our class to follow his way ...I guess your teacher wants to you to learn the recursive way of thinking in this exercise
    I'm gonna give u the algorithm of the code your supposed to implement.
    boolean isPalindrome(char[] x,int begin,int end)
    //if x[begin] equals to x[end]
    // return isPalindrome(x,begin+1,end-1)
    // else return false
    }Now every recursive function will need a terminal condition , this should go right at the beginning of the method. Your terminal condition(s) should be
    //if begin>=end return trueAnd yea , ur inital call to the function should be isPalindrome(original array , 0, original array -1)
    Edited by: darth_code_r on Nov 24, 2008 2:50 PM

  • Problems with String

    Hey All,
    I have this string "Straw? No, too stupid a fad, I put soot on warts" I am going to test is this string is a palindrome. Thi string is, but I run it through my program it says it is not because of the "?" and ",". How to take that string run it through something like a buffer or tokenizer to take out those things like "?" , "," and anything else. In the end I would like to have to remove all those types of characters and just run a string into the like I want to above to me change to this
    From:
    Straw? No, too stupid a fad, I put soot on warts
    To:
    Straw No too stupid a fad I put soot on warts

    You have to place a space in the replace(' ',' ') or it will not work. Plus it does not work with that, it just adds a space to what ever characeter I just replaced. Would a Stringtokenizer with a space delimiter take of my problem?

Maybe you are looking for

  • Waiting for a mouse click in a single thread

    Here's my problem: I'm working on a program I didn't initially create, and I picked it up from the rough midpoint of its evolution. It is a single thread AWT program, with a mouseListener interface already implemented. Here's my problem. In a game se

  • Connection Server does not start

    Hello guys, The Connection Server does not start anymore. When I always try to start it returns me a failed status and shows me that the server is considered failed because it has stopped 5 time(s) in 60 minute(s). It's a BOE XI 3.1 SP2 with IK 3.1 S

  • HttpSession vs. Stateful Session Bean ---- when State Session is large

    I hope most of the people come across with this issue where to put the state for the internet/intranet based applications when they are using servlet/jsps calling session beans. Weblogic 4.5.1 does support httpsession in-memory replication for the se

  • Call procedure's package from sql query ?

    Hi, I've write a package. In this package there is a procedure A with this parameters (in x, in y, out z). In the second procedure B, i want te create a cursor like this : 'select * from table where table.fiels in ( A.(x,y) )' Is it possible to do th

  • Macbook2.1, OS 10.4.8, Airport Extreme wont connect to Actiontec GT701-WG

    I can't get my macbook to connect to Qwest-DSL wireless gateway modem (Actiontec GT701-WG). A Dell laptop connects without any problems. I've tried a number of things: WEP, no WEP, Access lists. I've recycled the Actiontec, rebooted the macbook, etc.