adventofcode/2024/06/Part1.pm

66 lines
1.3 KiB
Perl
Raw Permalink Normal View History

2024-12-10 23:34:16 +00:00
package Part1;
use Math::Vector::Real;
use 5.36.0;
no warnings qw/ uninitialized /;
sub read_input ($file) {
my @grid = map { [ split '' ] } $file->lines({chomp=>1});
return \@grid;
}
my @directions = map { V(@$_) } [-1,0], [ 0,1], [1,0], [0,-1];
sub find_guard($grid) {
for my $i (0..$grid->$#* ) {
for my $j ( 0..$grid->[0]->$#* ) {
return V($i,$j) if $grid->[$i][$j] eq '^';
}
}
die "didn't find the guard!";
}
use List::AllUtils qw/ any /;
sub inside_grid($grid,$guard) {
return 0 if any { $_ < 0 } @$guard;
return $grid->[$guard->[0]][$guard->[1]];
}
sub solve ($grid) {
use DDP;
my $guard = find_guard($grid);
my $current_direction = 0;
use Clone qw/ clone /;
$grid = clone($grid);
my %seen;
$seen{"$guard"}++;
while() {
my $ahead = V(@$guard) + $directions[$current_direction];
last unless inside_grid($grid,$ahead);
if( $grid->[$ahead->[0]][$ahead->[1]] eq '#' ) {
$current_direction++;
$current_direction %= @directions;
redo;
}
$guard = $ahead;
$seen{"$guard"}++;
$grid->[$ahead->[0]][$ahead->[1]] = 'X';
}
use DDP;
# p %seen;
# p $guard;
# for my $l ( @$grid ) {
# say join '', @$l;
# }
return scalar keys %seen;
}
1;