So, here's how I approach developing an algorithm. I start with the problem statement and figure out how I would do it by hand. For your problem, you can easily sit in front of a piece of paper and solve the problem by hand -- do that and pay attention to how you're accomplishing the task.

I then solve a few simple examples by hand to verify that the algorithm makes sense. While I'm thinking about that, I look for repetitive tasks -- things that might go in a loop or subroutine. I look for nearly repetitive tasks -- things I could re-organize so that I could do those tasks with the others in a loop or a subroutine.

You can sit and think a little more: optimize this, do I really need to do that, is there a better way to do some or all of it? This part is optional, though, depending on the nature of the task and the time available to do it.

Unlike several of the responders, I hadn't seen this problem, before. Following this method, though, yielded both the iterative and the recursive solutions described by other posters in 10 to 15 minutes. Having a method to solve the problem helps you break out of the cycle of "Oh crap -- how am I going to solve this? If I don't solve this, I may flunk this class. I may not be cut-out to be a programmer. Yikes! I may not be cut-out to do anything. But I *like* to eat. Food, hmmm, I could use a cookie right now. And some cheese...".

Good luck!

--
Wade

In reply to Re^5: Recursion problem by wade
in thread Recursion problem by someone202

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.