diff options
| author | Lubos Kolouch <lubos@kolouch.net> | 2021-02-20 11:29:20 +0100 |
|---|---|---|
| committer | Lubos Kolouch <lubos@kolouch.net> | 2021-02-20 11:29:20 +0100 |
| commit | 0e1b3d96bc674d8c076d43c508c324f63340a74a (patch) | |
| tree | b705f0246ad629e7f0d979076dd0bf7fd7fb077a | |
| parent | 0682fba9a2de1142ff281c93ca066abc090c2ecc (diff) | |
| download | perlweeklychallenge-club-0e1b3d96bc674d8c076d43c508c324f63340a74a.tar.gz perlweeklychallenge-club-0e1b3d96bc674d8c076d43c508c324f63340a74a.tar.bz2 perlweeklychallenge-club-0e1b3d96bc674d8c076d43c508c324f63340a74a.zip | |
PWC 100 Task 2 Perl LK
| -rw-r--r-- | challenge-100/lubos-kolouch/perl/ch-2.pl | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/challenge-100/lubos-kolouch/perl/ch-2.pl b/challenge-100/lubos-kolouch/perl/ch-2.pl new file mode 100644 index 0000000000..e9bc3df9ed --- /dev/null +++ b/challenge-100/lubos-kolouch/perl/ch-2.pl @@ -0,0 +1,60 @@ +#!/usr/bin/perl +#=============================================================================== +# +# FILE: ch_2.pl +# +# USAGE: ./ch_2.pl +# +# DESCRIPTION: Perl Weekly Challenge #100 +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-100/ +# Triangle Sum +# +# AUTHOR: Lubos Kolouch +# CREATED: 2/20/2021 02:39:16 PM +#=============================================================================== + +use strict; +use warnings; + +sub min_sum { + my $what = shift; + + # + # 1 + # |\ + # 2 4 + # |\|\ + # 6 4 9 + # |\|\|\ + # 5 1 7 2 + + my $row_counter = 0; + my $min_path; + my %sums; + for my $row (@$what) { + $row_counter++; + my $col_counter = 0; + for my $item (@$row) { + $col_counter++; + my $min_sum; + + $min_sum = $sums{$row_counter-1, $col_counter} if exists($sums{$row_counter-1,$col_counter}); + $min_sum = $sums{$row_counter-1, $col_counter-1} if exists($sums{$row_counter-1,$col_counter-1}) and ( (not $min_sum) or ($sums{$row_counter-1,$col_counter-1} < $min_sum) ); + $min_sum //= 0; + + $sums{$row_counter,$col_counter} = $item + $min_sum; + + if ($row_counter == scalar @$what) { + $min_path = $item + $min_sum if ( (not $min_path) or ($item + $min_sum < $min_path)); + } + } + } + + return $min_path; +} +use Test::More; + +is( min_sum( [ [1], [ 2, 4 ], [ 6, 4, 9 ], [ 5, 1, 7, 2 ] ] ), 8 ); +is( min_sum( [ [3], [3,1], [5,2,3], [4,3,1,3] ] ), 7 ); + +done_testing; |
