commit 580df9e0a97f533bf1d6a8e949b80046f260b7f3
parent 25e9640fd228365b33db3e9bc126cf8287f20acd
Author: Samir Parikh <noreply@samirparikh.com>
Date: Tue, 27 Dec 2022 22:49:00 +0000
solve part 2 of day08
Diffstat:
M | day08/day08.pl | | | 63 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- |
1 file changed, 60 insertions(+), 3 deletions(-)
diff --git a/day08/day08.pl b/day08/day08.pl
@@ -16,7 +16,8 @@ foreach ( split /\n/, $input ) {
my $rows = scalar @trees;
my $columns = scalar @{ $trees[0] };
-my $part1 = ( 2 * $columns ) + 2 * ( $rows - 2 );
+my $visible = ( 2 * $columns ) + 2 * ( $rows - 2 );
+my @scenic_scores;
my %check = (
up => sub {
@@ -44,15 +45,71 @@ my %check = (
},
);
+my %view_distance = (
+ up => sub {
+ my ( $x, $y ) = @_;
+ my $distance = 0;
+ foreach my $yn ( reverse 0 .. $y - 1 ) {
+ $distance++;
+ if ( $trees[ $y ][ $x ] <= $trees[ $yn ][ $x ] ) {
+ last;
+ }
+ }
+ return $distance;
+ },
+
+ down => sub {
+ my ( $x, $y ) = @_;
+ my $distance = 0;
+ foreach my $yn ( $y + 1 .. $rows - 1 ) {
+ $distance++;
+ if ( $trees[ $y ][ $x ] <= $trees[ $yn ][ $x ] ) {
+ last;
+ }
+ }
+ return $distance;
+ },
+
+ left => sub {
+ my ( $x, $y ) = @_;
+ my $distance = 0;
+ foreach my $xn ( reverse 0 .. $x - 1 ) {
+ $distance++;
+ if ( $trees[ $y ][ $x ] <= $trees[ $y ][ $xn ] ) {
+ last;
+ }
+ }
+ return $distance;
+ },
+
+ right => sub {
+ my ( $x, $y ) = @_;
+ my $distance = 0;
+ foreach my $xn ( $x + 1 .. $columns - 1 ) {
+ $distance++;
+ if ( $trees[ $y ][ $x ] <= $trees[ $y ][ $xn ] ) {
+ last;
+ }
+ }
+ return $distance;
+ },
+);
+
for my $y ( 1 .. $rows - 2 ) {
for my $x ( 1 .. $columns - 2 ) {
foreach my $direction ( qw( up down left right ) ) {
if ( $check{ $direction }->( $x, $y ) ) {
- $part1++;
+ $visible++;
last;
}
}
+ my $scenic_score = 1;
+ foreach my $direction ( qw( up down left right ) ) {
+ $scenic_score *= $view_distance{ $direction }->( $x, $y );
+ }
+ push @scenic_scores => $scenic_score;
}
}
-say "part 1: ", $part1;
+say "part 1: ", $visible;
+say "part 2: ", max @scenic_scores;