64 lines
1.3 KiB
Perl
64 lines
1.3 KiB
Perl
|
use lib '.';
|
||
|
|
||
|
use Part1;
|
||
|
|
||
|
package Part2;
|
||
|
|
||
|
use 5.36.0;
|
||
|
use experimental 'declared_refs';
|
||
|
|
||
|
no warnings qw/ uninitialized /;
|
||
|
use List::AllUtils qw/ sum /;
|
||
|
|
||
|
sub read_input ($file) {
|
||
|
my ( $ordering, $manuals ) = split "\n\n", $file->slurp;
|
||
|
|
||
|
$ordering = [ map { [ split '\|' ] } split "\n", $ordering ];
|
||
|
|
||
|
$manuals = [ split "\n", $manuals ];
|
||
|
|
||
|
return { ordering => $ordering, manuals => $manuals };
|
||
|
}
|
||
|
|
||
|
use List::AllUtils qw/ first_index all /;
|
||
|
|
||
|
sub reshuffle_manual ( $ordering, $manual ) {
|
||
|
my @m = split ',', $manual;
|
||
|
|
||
|
my @ordering = grep {
|
||
|
my @o = @$_;
|
||
|
my $i = first_index { $_ == $o[0] } @m;
|
||
|
my $j = first_index { $_ == $o[1] } @m;
|
||
|
all { $_ > -1 } $i, $j;
|
||
|
} @$ordering;
|
||
|
|
||
|
my $redo = 1;
|
||
|
while ($redo) {
|
||
|
$redo = 0;
|
||
|
for my \@o(@ordering) {
|
||
|
my $i = first_index { $_ == $o[0] } @m;
|
||
|
my $j = first_index { $_ == $o[1] } @m;
|
||
|
|
||
|
next if $i < $j;
|
||
|
|
||
|
$redo = 1;
|
||
|
@m[ $i, $j ] = @m[ $j, $i ];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return join ',', @m;
|
||
|
}
|
||
|
|
||
|
sub solve ($input) {
|
||
|
return sum
|
||
|
map {
|
||
|
my @m = split ',';
|
||
|
$m[ @m / 2 ];
|
||
|
}
|
||
|
map { reshuffle_manual( $input->{ordering}, $_ ) }
|
||
|
grep { !Part1::good_manual( $input->{ordering}, $_ ) }
|
||
|
$input->{manuals}->@*;
|
||
|
}
|
||
|
|
||
|
1;
|