From e5eb8372a5d14fdcaca76dec539ffcb66ce3ba39 Mon Sep 17 00:00:00 2001 From: June McEnroe Date: Tue, 12 Dec 2023 12:37:44 -0500 Subject: Solve day 7 part 1 --- 2023/day07.pl | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 2023/day07.pl (limited to '2023') diff --git a/2023/day07.pl b/2023/day07.pl new file mode 100644 index 0000000..aa36965 --- /dev/null +++ b/2023/day07.pl @@ -0,0 +1,37 @@ +use strict; +use warnings; +sub handType { + my $hand = join("", sort(split(//, shift))); + return 7 if $hand =~ /(.)\g1{4}/; + return 6 if $hand =~ /(.)\g1{3}/; + return 5 if $hand =~ /(.)\g1{2}(.)\g2/ || $hand =~ /(.)\g1(.)\g2{2}/; + return 4 if $hand =~ /(.)\g1{2}/; + return 3 if $hand =~ /(.)\g1(.)\g2/ || $hand =~ /(.)\g1.(.)\g2/; + return 2 if $hand =~ /(.)\g1/; + return 1; +} +sub handRanks { + my %ranks = (T => 10, J => 11, Q => 12, K => 13, A => 14); + map { $ranks{$_} // $_ } split(//, shift); +} +sub handSort { + my $aType = handType($a); + my $bType = handType($b); + my @aRanks = handRanks($a); + my @bRanks = handRanks($b); + $aType <=> $bType || $aRanks[0] <=> $bRanks[0] || + $aRanks[1] <=> $bRanks[1] || $aRanks[2] <=> $bRanks[2] || + $aRanks[3] <=> $bRanks[3] || $aRanks[4] <=> $bRanks[4]; +} +my (@hands, %bids); +while (<>) { + my ($hand, $bid) = split(/ /); + push @hands, $hand; + $bids{$hand} = $bid; +} +my $winnings = 0; +my @ranked = sort handSort @hands; +for (0 .. $#ranked) { + $winnings += (1 + $_) * $bids{$ranked[$_]}; +} +print $winnings, "\n"; -- cgit 1.4.1