mandog has asked for the wisdom of the Perl Monks concerning the following question:
In the example below, recursion forms a bushy tree and works just fine. It is arguably easier to follow than a looping solution and is for all practical purposes just as fast.
The previous version of MS VC++ created executables with stack space of 4M. My 1987 data structure text observes that most modern computers like the PDP-11 (!) have a special stack register that makes sub routine calls relatively cheap.
Can somebody could come up with a looping solution to this problem (guess a number between two other numbers as quickly as possible) that was is as easy to follow and uses significantly less time or memory?
The world has many people who can either code better than I or who remember their school days better. I suspect it can be done...
use strict; use warnings; use diagnostics; # explain the warnings ! # guesses integet between two other integers sub recuGuess($$){ my($low,$high)=@_; my $mid=int (($low+$high)/2); print "is $mid low, high or correct? :"; my $ans=<STDIN>; $ans=uc(substr($ans,0,1)); if('C' eq $ans){ print "thank you for playing\n"; }elsif('L' eq $ans){ &recuGuess($mid+1,$high); }elsif('H' eq $ans){ &recuGuess($low,$mid-1); }else{ print "bad input\n"; &recuGuess($low,$high); } } recuGuess(1,40000);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: bushy recursion a good thing ?
by tye (Sage) on Sep 15, 2001 at 09:31 UTC | |
|
Re: bushy recursion a good thing ?
by John M. Dlugosz (Monsignor) on Sep 15, 2001 at 01:28 UTC | |
|
Re: bushy recursion a good thing ?
by blakem (Monsignor) on Sep 15, 2001 at 01:32 UTC | |
|
(dkubb) Re: (1) bushy recursion a good thing ?
by dkubb (Deacon) on Sep 15, 2001 at 02:53 UTC |