aoc2021

Advent of Code 2021 solutions in Perl.
git clone git://git.samirparikh.com/aoc2021
Log | Files | Refs | README

commit 8e66f05b398baf40c15fa401b840a2f8b9874753
parent bc0e4535045530a200ecbcef4bbaacc5d6cf141f
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Tue, 21 Dec 2021 16:49:13 +0000

get day09-2.pl to provide working solution for Day 09 Part 2

Diffstat:
Mday09-2.pl | 26+++++++++++++++++++-------
1 file changed, 19 insertions(+), 7 deletions(-)

diff --git a/day09-2.pl b/day09-2.pl @@ -13,8 +13,10 @@ sub find_basin { my $location = shift @queue; my $r = $location->[0]; my $c = $location->[1]; - my $location_height = $heightmap_ref->[$r][$c]; + my $location_height = $heightmap_ref->[$r][$c]; # can delete later say "checking location of $r, $c with height of $location_height"; + # don't want to double-count the initial lowpoint + $heightmap_ref->[$r][$c] = 9; # check surrounding locations for increase in height foreach my $offset ([0, -1], [0, 1], [-1, 0], [1, 0]) { my $neighbor_row = $r + $offset->[0]; @@ -22,11 +24,14 @@ sub find_basin { my $neighbor_height = $heightmap_ref->[$neighbor_row][$neighbor_col]; say "neighbor at $neighbor_row, $neighbor_col has height $neighbor_height"; next if ($neighbor_height == 9); - if ($neighbor_height == $location_height + 1) { # found increase - say "found winner"; - push @queue => [ $neighbor_row, $neighbor_col ]; # add neighbor to queue - $size++; - } + #if ($neighbor_height == $location_height + 1) { # found increase + say "found winner"; + # add neighbor coordinates to queue and set its height to 9 to prevent + # it from being checked again (double-counted) + push @queue => [ $neighbor_row, $neighbor_col ]; # add neighbor to queue + $heightmap_ref->[$neighbor_row][$neighbor_col] = 9; + $size++; + #} } } #say "row is $location->[0] and column is $location->[1]"; @@ -40,6 +45,7 @@ my $columns = @{$heightmap[0]}; push @heightmap => [ (9) x $columns ]; # add extra row of 9s my $rows = @heightmap; my $risk_level = 0; +my @basin_sizes; foreach my $row (0 .. $rows - 2) { # don't care about last row that we added foreach my $column (0 .. $columns - 2) { # don't care about the last column @@ -54,12 +60,18 @@ foreach my $row (0 .. $rows - 2) { # don't care about last row that we added } # found low point if ($lowpoint) { - say "found lowpoint of height $height at $row, $column"; + say "======================================"; + say "found lowpoint at $row, $column with height of $height"; $risk_level += $height + 1; my $basin_size = find_basin( $row, $column, \@heightmap ); say "basin size is $basin_size"; + push @basin_sizes => $basin_size; } } } say $risk_level; +# plain `sort` routine just sorts by strings in code point order +@basin_sizes = sort { $a <=> $b} @basin_sizes; +say "@basin_sizes"; +say $basin_sizes[-3] * $basin_sizes[-2] * $basin_sizes[-1];