Question

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));
    }
}
Était-ce utile?

La solution 2

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));
    }
}    

Autres conseils

Create a char[] of size K. Generate random() number between 0 to 25 and add 'a'. Now what ever char you generate just place it in begin and end and increase begin, decrement end. Do this till begin <= end.

public static String fun(int k){
        long seed = System.currentTimeMillis();
        Random random1 = new Random(seed);
        char[] a = new char[k];
        int begin=0, end=k-1;
        while(begin<=end){
            char c = (char)(random1.nextInt(26)+'a');
            a[begin]=c;
            a[end]=c;
            begin++;end--;
        }
        return String.valueOf(a);
    }

The call to random.nextInt() should not be placed outside the for loop, but inside of it. You don't necessarily need to use arrays. You can simply concatenate Strings (or use StringBuilder instead).

In the for loop you'd build the first half of the palindrome. Then, you can use the StringBuilder.reverse method in order to generate the second half.

Be aware of the middle letter, if your size is an odd number!

Also, your for loop should only run to the half of the size. Or (size - 1) / 2, if the size is an odd number.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top