adventofcode/2023/07/Part1.pm

61 lines
1.1 KiB
Perl
Raw Normal View History

2023-12-07 15:01:29 +00:00
use 5.38.0;
package Part1;
2023-12-07 15:33:30 +00:00
use List::AllUtils qw/ pairmap sum /;
2023-12-07 16:23:53 +00:00
use List::UtilsBy qw/ sort_by /;
2023-12-07 15:33:30 +00:00
2023-12-07 16:23:53 +00:00
sub rank_hand (@hand) {
2023-12-07 15:33:30 +00:00
@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;
2023-12-07 16:30:37 +00:00
if( grep { $_ == 3 } values %group ) {
return 5 if keys %group == 2;
return 4;
}
2023-12-07 15:33:30 +00:00
return 3 if keys %group == 3;
return 2 if keys %group == 4;
return 1;
}
2023-12-07 16:23:53 +00:00
sub handify ($str) {
2023-12-07 15:33:30 +00:00
state %map = (
'T' => 10,
'J' => 11,
'Q' => 12,
'K' => 13,
2023-12-07 16:23:53 +00:00
A => 14
2023-12-07 15:33:30 +00:00
);
2023-12-07 16:30:37 +00:00
return [
map { chr( ord('a') + $_ - 2 ) } map { $map{$_} // $_ } split '', $str
];
2023-12-07 15:33:30 +00:00
}
2023-12-07 16:23:53 +00:00
sub parse_input ($input) {
2023-12-07 16:30:37 +00:00
return pairmap {
2023-12-07 16:23:53 +00:00
[ handify($a), $b ]
}
2023-12-07 16:30:37 +00:00
map { split " " } split "\n", $input;
2023-12-07 15:33:30 +00:00
}
2023-12-07 16:23:53 +00:00
sub score (@hand) {
2023-12-07 15:33:30 +00:00
join '', rank_hand(@hand), @hand;
}
2023-12-07 15:01:29 +00:00
sub solution_1 ($input) {
2023-12-07 16:23:53 +00:00
my $rank = 0;
2023-12-07 16:30:37 +00:00
return sum map { ++$rank * $_->[1] } sort_by { score( $_->[0]->@* ) } parse_input($input);
2023-12-07 15:01:29 +00:00
}
1;