In this node started by Anonymous Monk the majority opinion seemed to be that recursion was at best a party trick. At least according to the friendly folks in the average CS 102 class, recursion is a good thing. (Unless your recursion forms a chain the way the original poster’s did).

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);


--mandog

In reply to bushy recursion a good thing ? by mandog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.