main
Yanick Champoux 2023-12-01 12:04:34 -05:00
parent 95754d7b78
commit 95fc42626a
3 changed files with 98 additions and 0 deletions

16
2023/01/Part1.pm Normal file
View File

@ -0,0 +1,16 @@
use 5.38.0;
package Part1;
use List::AllUtils qw/ sum /;
sub extract_number ($line) {
my @n = $line =~ /(\d)/g;
return join "", $n[0], $n[-1];
}
sub solution_1 ($input) {
sum map { extract_number($_) } split "\n", $input;
}
1;

33
2023/01/Part2.pm Normal file
View File

@ -0,0 +1,33 @@
use 5.38.0;
package Part2;
use Part1;
use List::AllUtils qw/ sum /;
my %spelled = (
one => 1,
two => 2,
three => 3,
four => 4,
five => 5,
six => 6,
seven => 7,
eight => 8,
nine => 9,
);
sub resolve_spelled_numbers ($line) {
my $re = join '|', keys %spelled, 1 .. 9;
join "", map { $spelled{$_} // $_ } $line =~ /^.*?($re)/g,
$line =~ /^.*($re)/g;
}
sub solution_2 ($input) {
sum map { Part1::extract_number($_) }
map { resolve_spelled_numbers($_) } split "\n", $input;
}
1;

49
2023/01/test.t Normal file
View File

@ -0,0 +1,49 @@
use 5.38.0;
use Test2::V0;
use Path::Tiny;
use Part1;
use Part2;
my $input = path('input')->slurp;
my %sample = (
'1abc2' => 12,
pqr3stu8vwx => 38,
a1b2c3d4e5f => 15,
treb7uchet => 77
);
for my ( $line, $expected ) (%sample) {
is Part1::extract_number($line) => $expected;
}
is Part1::solution_1($input) => 56397;
subtest 'part 2' => sub {
is Part2::resolve_spelled_numbers("sixsixsix") => 66;
%sample = (
'two1nine' => 29,
eightwothree => 83,
abcone2threexyz => 13,
xtwone3four => 24,
'4nineeightseven2' => 42,
zoneight234 => 14,
'7pqrstsixteen' => 76,
'twothreefour' => 24,
);
for my ( $line, $expected ) (%sample) {
is Part1::extract_number( Part2::resolve_spelled_numbers($line) ) =>
$expected;
}
is Part2::solution_2($input) => 55701;
};
done_testing;