Saturday, June 21, 2008

Recursion continued

A friend of mine likes Palindromes, and was trying to figure out a way of seeing which sentences are Palindromes from a list of combinations of words. I don't exactly know how the combination maker works, but that part is recursive.

The part of his code that checks for a Palindrome is iterative, however. It checks the String from its beginning and its end, and makes comparisons based on those. If a letter pair doesn't match, it terminates. Otherwise it returns true.

It's pretty fast.

My recursive method, on the other hand, takes a String and splits it into two halves, and reverses the second half (so that ecar = race), and then does comparisons based on that.

It's pretty slow. But its also turning up an extra Palindrome or two every now and then. Which I think has to do with how its doing its calculations.

If I could somehow optimize my recursion to break if it knows its false i could probably speed it up greatly.

Which one's better? I don't know.

Also, for if tests, especially when calling a method in a return line, I think I found a pretty nifty way of indenting my code.

take

function foo (int num) {
if (num == 0) {
return 1;
}
else {
return
1
+ foo(num--);
}
}


i think this is a lot better than

function bar(int num) {
if (num == 0)
return 1;
else return 1 + bar(num--);
}

With the former, you can easily tell that it's returning a number and then calling itself. With the latter, you have to take in both as one step. This isn't so bad at first, but when you have something like


public String flip(String word) {
if (word.length() ==1) {
return
word.substring(word.length() - 1, word.length());
}

else {
return
word.substring(word.length() - 1, word.length())
+ flip(word.substring(0, word.length() - 1));
}
}


Where the return statements get a little long winded, it can be quite nice to break them up into smaller pieces. Of course, all the indention can get a little long winded, but, indenting has always been a sign that you're going a little bit deeper into the logic of an operation (nested if tests, nested loops, etc)

Since recursion breaks down a problem into its subproblems, and then returns a combined result, I believe this way makes sense, too. When you break a problem into a smaller part, you're going further into the logic... When you're done, you're coming out.

No comments: