I've been looking around for awhile now, and I haven't found anything that helped me. I have to write a program that uses one method (the main method) to read in the size of/and elements of an array. Then I must write a recursive method titled "forwardsEqualBackwards" which returns true if the elements of the array can be read the same way regardless of whether the array is read forwards or backwards (it's a a test to see whether or not it's a palindrome) and false otherwise.
Asked
Active
Viewed 179 times
-1
-
See this link: http://stackoverflow.com/questions/4367260/creating-a-recursive-method-for-palindrome-in-java – Maroun Nov 29 '12 at 07:38
2 Answers
2
pseudocode:
bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0)
{
if (indexToLookAt >= length-indexToLookAt-1)
return true; //reached end of recursion
if (a[indexToLookAt] == a[length-indexToLookAt-1])
return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here
else
return false;
}
forwardsEqualBackwards("",0); //returns true
forwardsEqualBackwards("a",1); //returns true
forwardsEqualBackwards("otto",4); //returns true
forwardsEqualBackwards("otsto",5); //returns true
forwardsEqualBackwards("otstou",5); //returns false

Philipp
- 11,549
- 8
- 66
- 126
-
Apologies. It has to be a static recursive method. Still. This was very helpful and I thank you. What I don't understand is that the array won't read into the recursive method from the main method. So I can't look at the contents of the array within the recursive method. – Christopher Lhama Rowse Nov 29 '12 at 07:39
-
this is pseudo code. You can make the method static if you want. Either you pass the array as an argument (as I did) or you have a static variable which is accessed by both main and the recursive function. – Philipp Nov 29 '12 at 07:46
1
bool method(int start, int end)
{
if(start<=end)
{
if(Array[start]!=array[end])
return false;
return method(start+1, end-1)
}
return true;
}

Muhammad Tauseef
- 413
- 2
- 6
- 18