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.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; } }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |