Merge branch '2019-01'

main
Yanick Champoux 2023-12-01 12:38:22 -05:00
commit f8db5b1077
5 changed files with 138 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;

38
2023/01/benchmark.pl Normal file
View File

@ -0,0 +1,38 @@
use 5.38.0;
use Benchmark ':hireswallclock';
use Path::Tiny;
use JSON qw/ to_json /;
use DateTime;
use Part1;
use Part2;
my @parts = (
{ part => 1, sub => \&Part1::solution_1, expected => 56397 },
{ part => 2, sub => \&Part2::solution_2, expected => 55701 },
);
my $input = path('./input')->slurp;
for my $part (@parts) {
my $res = Benchmark::countit(
10,
sub {
$part->{sub}->($input) == $part->{expected} or die;
}
);
my $result = {
day => 1,
year => 2023,
#variant => '',
language => 'perl',
part => $part->{part},
time => $res->cpu_a / $res->iters,
timestamp => DateTime->now->iso8601,
};
say to_json $result;
}

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;

2
2023/benchmark.json Normal file
View File

@ -0,0 +1,2 @@
{"language":"perl","time":0.00189813978688821,"part":1,"day":1,"year":2023,"timestamp":"2023-12-01T17:35:46"}
{"language":"perl","part":2,"time":0.00721379310344828,"day":1,"year":2023,"timestamp":"2023-12-01T17:35:58"}