Ok, I had a lab assigned to me which detailed many different situations in which I had to use recursion in order to solve them. Most of them were pretty simple. However I've been stuck on this Palindrome problem for hours.
I know most people's Palindrome issues are with proving whether a string is a Palindrome or not. This is NOT one of those problems. According to my teacher I must "Write a method that recursively generates random palindromes. The desired length of the palindrome in characters should be a parameter in your method"
At first I thought it would be a piece of cake and I set program up like this:
public class Recursion
{
public static String Palindrome(int length)
{
//Alphabet to pick letters from
String alpha="abcdefghijklmnopqrstuvwxyz";
String s="";
String sBackwards=" ";
if(length==0)
sBackwards+=reverse(s);
return sBackwards;
//recursion over-rides sBackwards
else
{
Random r = new Random();
//places a char from alpha into s
s+=(alpha.charAt((int)r.nextInt(26)));
System.out.print(s);
return Palindrome(length-1); //recursion
}
}
public static void main(String args[])
{
System.out.println(Palindrome(10));
}
}
This code accurately generates a string of 10 random characters by using recursion. I did not include the method to reverse the string as I have tested it and know that it works.
Example of output: cjxpkgaljs
Neccessary output: cjxpkgaljs sjlagkpxjc
However what I found to be the problem was reversing the string in the Palindrome method. I have a reverse method which will reverse a string. However I have the issue that everytime the method calls itself it creates String s="";
because of that I can never take the full complete string and reverse it. Rather I can only print out 1 character at a time.
Does anyone have a direction they can point me in so that I can try to solve this problem?
The method must use recursion however the Palindrome method does not have to be static. I know it's rather rude that my first post is a post requiring help from people however I would like to try to get help else where as my teacher doesn't have office hours tommorow. But the whole lab isn't due until Sept. 12th, I just want to see if I can solve this problem without meeting her in her office as she isn't exactly the easiest to understand...
Thanks for the help.