Memoize will work, but it's not magic. The simplest way to write the function is as follows:
sub get_move_score { my @numbers = @_ or return("end", "", 0); return "shift", $numbers[0], $numbers[0] if 1 == @numbers; my $shift = shift @numbers; my $pop = pop @numbers; my $score_shift = $shift - (get_move_score(@numbers, $pop))[2]; my $score_pop = $pop - (get_move_score($shift, @numbers))[2]; if ($score_pop > $score_shift) { return "pop", $pop, $score_pop; } else { return "shift", $shift, $score_shift; } }
Now if you memoize that and try to run it for a list of n numbers, the memory requirements are O(n**3). (You wind up calling it for O(n) starting points, with O(n) ending points, with an argument list of length O(n) passed in.) For a list of 1000 numbers, that means that you'll need to store order of a billion or so numbers. (Less a factor of 6 or so, I could work it out.) Given how Perl hogs memory, and what most PCs are capable of, your implementation will probably fail on account of running out of memory.

You can fix that by having @numbers be in a global array, and then only pass in the start and end points of the list. But now if you want to play more than one game, you're hosed. (Unless you read the documentation for Memoize, and correctly call memoize/unmemoize in pairs.)

Which means that in this case it is better to understand what the program is supposed to do, and explicitly build up your own data structure.


In reply to Re^3: Puzzle: Given an array of integers, find the best sequence of pop / shift... by tilly
in thread Puzzle: Given an array of integers, find the best sequence of pop / shift... by TedPride

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.