adventofcode/2023/03/Part1.pm
2023-12-03 15:12:17 -05:00

46 lines
974 B
Perl

use 5.38.0;
package Part1;
use List::AllUtils qw/pairmap max sum /;
sub find_numbers($line) {
my @entries;
while ( $line =~ /\d+/g ) {
push @entries => {
prefix => length $`,
length => length $&,
n => 0+$&,
};
}
return @entries;
}
sub near_symbol($numb,$lines) {
no warnings;
my $surrounding = join "", map {
substr $lines->[$_+$numb->{line}],
max($numb->{prefix}-1,0),
$numb->{length}+2
} -1..1;
return $surrounding =~ /[^.\d]/;
}
sub numbers_near_symbols($input) {
my @lines = split "\n", $input;
unshift @lines, '';
my @numbers = pairmap { map { +{ %$_, line => $a } } @$b } map { $_ => [find_numbers($lines[$_])] } 1..$#lines;
@numbers = grep { near_symbol($_,\@lines) } @numbers;
return @numbers;
}
sub solution_1 ($input) {
my @numbers = numbers_near_symbols($input);
return sum map { $_->{n}} @numbers;
}
1;