Re: factorial n! program
- From: "James Giles" <jamesgiles@xxxxxxxxxxxxxxxx>
- Date: Tue, 26 Sep 2006 17:54:40 GMT
blmblm@xxxxxxxxxxxxx wrote:
In article <efak4o$apr$1@xxxxxxxxxxxxxxxxx>,....
There are better ways to make recursion interesting. Think
of a binary tree you have set up, and now want to visit all
the nodes. [...]
Indeed! exactly the examples I use to try to convince hardened
"wouldn't it be easier to just write a loop?" types ....
That's one of the examples I always use to point out the
advantages of not doing recursion. A depth-first tree
traversal is just a loop around a stack. If you use recursion,
the stack is automatic and the code is barely a little simpler.
The loop form is usually noticably faster.
But, suppose you want to traverse the tree width-first? The
loop-based algorithm is easy to modify: replace the stack
with a queue. That's all you do. You're still guaranteed to
traverse the whole tree (and it uses less space than depth-first
if the tree is narrow and deep). How do you do that with
recursion?
Suppose you want to traverse the loop in some other order
by prioritizing the subtrees (say, by the likelyhood of finding
an interesting node - a common thing in game trees), you sort
the queue between steps (or use the partial order that's used
by heapsort) so the next node is the highest priority. How
do you do that with recursion?
The fact is that recursion hides the fact that different search
orders are symmetric with depth-first based on what intermediate
store you use for the nodes that have yet to be traversed. This
biases your approach to solving problems involving trees.
--
J. Giles
"I conclude that there are two ways of constructing a software
design: One way is to make it so simple that there are obviously
no deficiencies and the other way is to make it so complicated
that there are no obvious deficiencies." -- C. A. R. Hoare
.
- References:
- factorial n! program
- From: Sandrus
- Re: factorial n! program
- From: Sandrus
- Re: factorial n! program
- From: Elijah Cardon
- Re: factorial n! program
- From: Dieter Britz
- Re: factorial n! program
- From: blmblm
- factorial n! program
- Prev by Date: Re: silverfrost IDE
- Next by Date: Re: sequence derived type in common block
- Previous by thread: Re: factorial n! program
- Next by thread: Re: factorial n! program
- Index(es):
Relevant Pages
|