summary refs log tree commit diff homepage
diff options
context:
space:
mode:
-rw-r--r--2023/day07.pl37
1 files changed, 37 insertions, 0 deletions
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";