#!/usr/local/bin/perl # day 2022-08 use strict; use warnings; use v5.32; use List::Util qw( max ); @ARGV = "input" unless @ARGV; chomp( my $input = do { local $/; <> } ); my @trees; foreach ( split /\n/, $input ) { push @trees => [ split //, $_ ]; } my $rows = scalar @trees; my $columns = scalar @{ $trees[0] }; my $visible = ( 2 * $columns ) + 2 * ( $rows - 2 ); my @scenic_scores; my %check = ( up => sub { my ( $x, $y ) = @_; return ( $trees[ $y ][ $x ] > max( map { $trees[ $_ ][ $x ] } ( 0 .. $y - 1 ) ) ); }, down => sub { my ( $x, $y ) = @_; return ( $trees[ $y ][ $x ] > max( map { $trees[ $_ ][ $x ] } ( $y + 1 .. $rows - 1 ) ) ); }, left => sub { my ( $x, $y ) = @_; return ( $trees[ $y ][ $x ] > max( map { $trees[ $y ][ $_ ] } ( 0 .. $x - 1 ) ) ); }, right => sub { my ( $x, $y ) = @_; return ( $trees[ $y ][ $x ] > max( map { $trees[ $y ][ $_ ] } ( $x + 1 .. $columns - 1 ) ) ); }, ); 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 ) ) { $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: ", $visible; say "part 2: ", max @scenic_scores;