1nict:

Here ya go! (In readmore tags, just in case it would be a spoiler for someone...)

#!env perl # # PWC_100_min_path_sum.pl # # Return the path with the smallest sum from the top of the triangle t +o the bottom. # # 20210215 use strict; use warnings; my @triangle = ( [1], [2, 4], [6, 4, 9], [5, 1, 7, 2], ); sub p { my $L = shift; return "$L->[0] (", join(", ", @{$L->[1]}), ")"; } # Given a coordinate, return an array ref where the first item is the +sum of the # shortest path, and the second item is the path (from bottom to top) sub f { my ($r, $c) = @_; my $val = $triangle[$r][$c]; # If there are no more rows to check, then return the column return [ $val, [ $val ] ] unless defined $triangle[$r+1]; die "Invalid data structure! ($r,$c)" unless defined $triangle[$r+ +1][$c]; my $L = f($r+1, $c); if (defined $triangle[$r+1][$c+1]) { my $R = f($r+1, $c+1); $L = $R if $R->[0] < $L->[0]; } $L->[0] += $val; push @{$L->[1]}, $val; return $L; } my $result = f(0,0); print "Result: ", p($result), "\n";

Running it gives:

$ perl PWC_100_min_path_sum.pl Result: 8 (1, 4, 2, 1)

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: Brute force vs algorithm (PWC # 100) by roboticus
in thread Brute force vs algorithm (PWC # 100) by 1nickt

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.