Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners palindrome array problem

Have Programming Question? Ask it here!
 
 
 


Gabriel Dos Santos
palindrome array problem
2 Answer(s)      a year and 10 months ago
Posted in : Java Beginners


I'm having trouble figuring this assignment out. Can someone please help me?

Generate (write the code) and save in an array Palidrome[250][5] all the 5 letter words using {a, b, c}

Write the code and show the execution for:

a.) Count the number of palindromes in this set.

b.) Print out all the palindromes where a letter appears more than twice.

   Examples a a b a a ;  b b b b b;  c a c a c;   a b b b a   etc.

c.) Print out all the palindromes where a letter appears no more than twice.

Examples a b c b a; a c b c a etc.


Advertisement
View Answers

October 10, 2012 at 12:57 PM


Here is a code that displays all the 5 letter words using {a, b, c}and display the palindromes from them.

public class GeneratePalindromes{
    static boolean isPalindrome(String s){
        int left = 0;
        int right = s.length() - 1;
        while (left < right){
        if (s.charAt(left) != s.charAt(right))
        return false;
        left++;
        right--;
        }
        return true;
    }
    public static void main(String[] args){
        char[] chars = "abc".toCharArray();
        int len = 5;
        System.out.println("Display all the words: ");
        iterate(chars, len, new char[len], 0);
        System.out.println("Display all the palindromes: ");
        checkPalin(chars, len, new char[len], 0);
    }
    public static void iterate(char[] chars, int len, char[] build, int pos) {
            if (pos == len) {
            String word = new String(build);
            System.out.println(word);
            return;
            }
           for(int i = 0; i < chars.length; i++) {
            build[pos] = chars[i];
            iterate(chars, len, build, pos + 1);
        }
    }
     public static void checkPalin(char[] chars, int len, char[] build, int pos) {
            if(pos == len) {
            String word = new String(build);
            if(isPalindrome(word)){
            System.out.println(word);
            }
            return;
        }
           for(int i = 0; i < chars.length; i++) {
            build[pos] = chars[i];
            checkPalin(chars, len, build, pos + 1);
        }
    }
}


October 10, 2012 at 7:22 PM


Thank you so much!



Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com