diff --git a/2023/07/Part1.pm b/2023/07/Part1.pm index c9b4e65..5051721 100644 --- a/2023/07/Part1.pm +++ b/2023/07/Part1.pm @@ -2,10 +2,63 @@ use 5.38.0; package Part1; -use List::AllUtils qw/ /; +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; + + #use DDP; p %group; + + return 7 if 1 == keys %group; + + return 6 if grep { $_ == 4 } values %group; + + return 5 if keys %group == 2 and grep { $_ == 3 } values %group; + + return 4 if grep { $_ == 3 } values %group; + + 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 + ); + + 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_1 ($input) { - ...; + my @hand_score = sort_by { score($_->[0]->@*) } parse_input($input); + my $rank = 0; + # use DDP; p @hand_score; + return sum map { ++$rank * $_->[1] } @hand_score; } 1; diff --git a/2023/07/example b/2023/07/example new file mode 100644 index 0000000..e3500c3 --- /dev/null +++ b/2023/07/example @@ -0,0 +1,5 @@ +32T3K 765 +T55J5 684 +KK677 28 +KTJJT 220 +QQQJA 483 diff --git a/2023/07/part1.t b/2023/07/part1.t index ae7365e..3f86a4e 100644 --- a/2023/07/part1.t +++ b/2023/07/part1.t @@ -7,7 +7,21 @@ use Path::Tiny; use Part1; my $input = path('input')->slurp; +my $example = path('example')->slurp; +is Part1::rank_hand( 'AAAAA') => 7; +is Part1::rank_hand( 'AA8AA') => 6; +is Part1::rank_hand( '23332') => 5; +is Part1::rank_hand( 'TTT98') => 4; +is Part1::rank_hand( '23432') => 3; +is Part1::rank_hand( 'A23A4') => 2; +is Part1::rank_hand( '23456') => 1; + +is [ Part1::parse_input( '2345A 123') ] => [ +[ [qw/ a b c d m /], 123 ] +]; + +is Part1::solution_1($example) => 6440; is Part1::solution_1($input) => 'TODO'; done_testing; diff --git a/2023/07/solutions.yml b/2023/07/solutions.yml index 67055f3..1f1ab68 100644 --- a/2023/07/solutions.yml +++ b/2023/07/solutions.yml @@ -1,2 +1,2 @@ -1: TODO +1: 250058342 2: TODO