From 95fc42626aac6eb13d82c89e72d963280ce43bca Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Fri, 1 Dec 2023 12:04:34 -0500 Subject: [PATCH] 2023-01 --- 2023/01/Part1.pm | 16 ++++++++++++++++ 2023/01/Part2.pm | 33 ++++++++++++++++++++++++++++++++ 2023/01/test.t | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 2023/01/Part1.pm create mode 100644 2023/01/Part2.pm create mode 100644 2023/01/test.t diff --git a/2023/01/Part1.pm b/2023/01/Part1.pm new file mode 100644 index 0000000..fe998cc --- /dev/null +++ b/2023/01/Part1.pm @@ -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; diff --git a/2023/01/Part2.pm b/2023/01/Part2.pm new file mode 100644 index 0000000..465d939 --- /dev/null +++ b/2023/01/Part2.pm @@ -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; diff --git a/2023/01/test.t b/2023/01/test.t new file mode 100644 index 0000000..3a52d7d --- /dev/null +++ b/2023/01/test.t @@ -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;