summary refs log tree commit diff homepage
path: root/2021
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2021-12-03 10:29:58 -0500
committerJune McEnroe <june@causal.agency>2021-12-03 10:29:58 -0500
commitfeb34fac48dac79881bff93a2e60e69a08e432a2 (patch)
tree9b6a75a02fbf276f0cc84154bcaf8d167e58ffac /2021
parentSolve day 3 part 1 (diff)
downloadaoc-feb34fac48dac79881bff93a2e60e69a08e432a2.tar.gz
aoc-feb34fac48dac79881bff93a2e60e69a08e432a2.zip
Solve day 3 part 2
Diffstat (limited to '2021')
-rw-r--r--2021/day03.pl32
1 files changed, 26 insertions, 6 deletions
diff --git a/2021/day03.pl b/2021/day03.pl
index 8a62021..7e8d2fc 100644
--- a/2021/day03.pl
+++ b/2021/day03.pl
@@ -1,17 +1,37 @@
 use strict;
 use warnings;
-my @nums;
+my ($bits, @nums);
 while (<>) {
 	chomp;
+	$bits = length($_);
 	push @nums, oct("0b".$_);
 }
-my $gamma = 0;
-for (my $i = 0; $i < 12; $i++) {
+sub countOnes {
+	my $i = shift;
 	my $ones = 0;
-	foreach (@nums) {
+	foreach (@_) {
 		$ones++ if $_ & (1 << $i);
 	}
-	$gamma |= 1 << $i if $ones > @nums / 2;
+	$ones;
+}
+my $gamma = 0;
+for (my $i = 0; $i < $bits; $i++) {
+	$gamma |= 1 << $i if countOnes($i, @nums) > @nums / 2;
 }
-my $epsilon = ~$gamma & 0xFFF;
+my $epsilon = ~$gamma & ((1 << $bits) - 1);
 print $gamma * $epsilon, "\n";
+my @o2 = @nums;
+my $i = $bits - 1;
+while (@o2 > 1) {
+	my $most = (countOnes($i, @o2) >= @o2 / 2) << $i;
+	@o2 = grep { ($_ & (1 << $i)) == $most } @o2;
+	$i--;
+}
+my @co2 = @nums;
+$i = $bits - 1;
+while (@co2 > 1) {
+	my $least = !(countOnes($i, @co2) >= @co2 / 2) << $i;
+	@co2 = grep { ($_ & (1 << $i)) == $least } @co2;
+	$i--;
+}
+print $o2[0] * $co2[0], "\n";