adventofcode/2023/07/Part1.pm
2023-12-07 11:30:37 -05:00

61 lines
1.1 KiB
Perl

use 5.38.0;
package Part1;
use List::AllUtils qw/ pairmap sum /;
use List::UtilsBy qw/ sort_by /;
sub rank_hand (@hand) {
@hand = split '', shift @hand if @hand == 1;
my %group;
$group{$_}++ for @hand;
return 7 if 1 == keys %group;
return 6 if grep { $_ == 4 } values %group;
if( grep { $_ == 3 } values %group ) {
return 5 if keys %group == 2;
return 4;
}
return 3 if keys %group == 3;
return 2 if keys %group == 4;
return 1;
}
sub handify ($str) {
state %map = (
'T' => 10,
'J' => 11,
'Q' => 12,
'K' => 13,
A => 14
);
return [
map { chr( ord('a') + $_ - 2 ) } map { $map{$_} // $_ } split '', $str
];
}
sub parse_input ($input) {
return pairmap {
[ handify($a), $b ]
}
map { split " " } split "\n", $input;
}
sub score (@hand) {
join '', rank_hand(@hand), @hand;
}
sub solution_1 ($input) {
my $rank = 0;
return sum map { ++$rank * $_->[1] } sort_by { score( $_->[0]->@* ) } parse_input($input);
}
1;