Search code examples
javarandompalindrome

Random Palindrome Generator Java


I am having some trouble with figuring out how to work on making a palindrome generator from random letters. e.g. asdffdsa, kiutgtuik. I need to have the size be entered and use that to make the palindrome. I have some code already, and was just curious if you could help point me in the right direction. I would also like to try and not use arrays either for this.

import java.util.Random;

public class PP425 {
    public static String generatePalindrome (int size) {
        Random rand = new Random();
        char ch = (char)(rand.nextInt(26) + 97);
        String random = "";
        for (int i = 0; i < size; i++) {

        }


        return random;
    }
    public static void main(String[] args) {
        System.out.println(generatePalindrome(3));
    }
}

Solution

  • Is this what you want? If for long size, use StringBuilder instead of String.

    import java.util.Random;
    
    public class PP425 {
        public static String generatePalindrome (int size) {
            Random rand = new Random();
            StringBuilder random = new StringBuilder(size);
            for (int i = 0; i < (int)Math.ceil((double)size/2); i++) {
                char ch = (char)(rand.nextInt(26) + 97);
                random.append(ch);
            }
            for(int i = size/2-1; i >= 0; i--)
                random.append(random.charAt(i));
    
            return random.toString();
        }
        public static void main(String[] args) {
            System.out.println(generatePalindrome(3));
        }
    }