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);
In reply to bushy recursion a good thing ? by mandog
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |