69 lines
1.2 KiB
Perl
69 lines
1.2 KiB
Perl
use 5.38.0;
|
|
|
|
package Part2;
|
|
|
|
use Part1;
|
|
|
|
use List::AllUtils qw/ pairmap sum max /;
|
|
use List::UtilsBy qw/ sort_by /;
|
|
|
|
sub rank_hand(@hand) {
|
|
@hand = split '', shift @hand if @hand == 1;
|
|
|
|
my %group;
|
|
$group{$_}++ for @hand;
|
|
|
|
my $jokers = delete $group{'`'} // 0;
|
|
|
|
return 7 if 1 >= keys %group;
|
|
|
|
return 6 if grep { $_+$jokers >= 4 } values %group;
|
|
|
|
my $max = max values %group;
|
|
|
|
if( $max + $jokers >= 3 ) {
|
|
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' => 1,
|
|
'Q' => 12,
|
|
'K' => 13,
|
|
A => 14
|
|
);
|
|
|
|
my @cards = map { chr( ord('a') + $_ - 2 )} map { $map{$_} // $_ } split '', $str;
|
|
|
|
return \@cards;
|
|
}
|
|
|
|
sub parse_input($input) {
|
|
my @lines = split "\n", $input;
|
|
my @hand_score = pairmap {
|
|
[ handify($a), $b]
|
|
} map { split " " } @lines;
|
|
return @hand_score;
|
|
}
|
|
|
|
sub score(@hand) {
|
|
join '', rank_hand(@hand), @hand;
|
|
}
|
|
|
|
sub solution_2 ($input) {
|
|
my @hand_score = sort_by { score($_->[0]->@*) } parse_input($input);
|
|
my $rank = 0;
|
|
return sum map { ++$rank * $_->[1] } @hand_score;
|
|
}
|
|
|
|
1;
|