summary refs log tree commit diff homepage
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2023-12-12 12:37:44 -0500
committerJune McEnroe <june@causal.agency>2023-12-12 12:37:44 -0500
commite5eb8372a5d14fdcaca76dec539ffcb66ce3ba39 (patch)
tree61285a8f3d360705cd03d2b46b1bb97265b8fdc2
parentSolve day 6 part 2 (diff)
downloadaoc-e5eb8372a5d14fdcaca76dec539ffcb66ce3ba39.tar.gz
aoc-e5eb8372a5d14fdcaca76dec539ffcb66ce3ba39.zip
Solve day 7 part 1
-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";