This commit is contained in:
Yanick Champoux 2024-12-11 13:40:40 -05:00
parent 919f966ec3
commit f998add903
4 changed files with 99 additions and 0 deletions

49
2024/11/Part1.pm Normal file
View File

@ -0,0 +1,49 @@
use lib '../../perl-lib';
use 5.36.0;
package Part1;
use List::AllUtils qw/ sum /;
use Moo;
extends 'AoC::Puzzle';
has '+input' => default => sub ($self) {
[ split ' ', $self->path_file->slurp ];
};
has nbr_iterations => is => 'ro', default => 25;
sub evolve ( $self, $stone ) {
return (1) if $stone == 0;
return ( $stone * 2024 ) if length($stone) % 2;
my $x = $stone % 10**( length($stone) / 2 );
my $y = int( $stone / 10**( length($stone) / 2 ) );
return ( $y, $x );
}
sub print_line ( $self, @stones ) {
say join " ", @stones;
}
sub solve ($self) {
my @stones = $self->input->@*;
my %stones;
$stones{$_}++ for @stones;
for ( 1 .. $self->nbr_iterations ) {
my %new_stones;
for my $stone ( keys %stones ) {
$new_stones{$_} += $stones{$stone} for $self->evolve($stone);
}
%stones = %new_stones;
}
return sum values %stones;
}
1;

13
2024/11/Part2.pm Normal file
View File

@ -0,0 +1,13 @@
use lib '.';
use 5.36.0;
package Part2;
use Moo;
extends 'Part1';
has '+nbr_iterations' => default => 75;
1;

16
2024/11/benchmark.pl Executable file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env perl
use 5.36.0;
use Benchmark qw/ timethis timeit /;
use lib qw~ . ~;
use Part1;
use Part2;
use Path::Tiny;
use File::Serialize;
my $res;
$res = timethis(0, sub { Part1->new(file=>'input')->solve }, 'part 1');
$res = timethis(0, sub { Part2->new(file=>'input')->solve }, 'part 2');

21
2024/11/test.t Normal file
View File

@ -0,0 +1,21 @@
use lib qw~ . ~;
use Part1;
use Part2;
use Test2::V0;
use Path::Tiny;
use File::Serialize;
my $solutions = deserialize_file './solutions.yml';
subtest 'part 1' => sub {
is( Part1->new(input=>[125,17])->solve() => 55312 );
is( Part1->new(file=>'input')->solve() => $solutions->{part1} );
};
subtest 'part 2' => sub {
is( Part2->new(file=>'input')->solve() => $solutions->{part2});
};
done_testing();