diff options
author | June McEnroe <june@causal.agency> | 2021-12-03 10:29:58 -0500 |
---|---|---|
committer | June McEnroe <june@causal.agency> | 2021-12-03 10:29:58 -0500 |
commit | feb34fac48dac79881bff93a2e60e69a08e432a2 (patch) | |
tree | 9b6a75a02fbf276f0cc84154bcaf8d167e58ffac | |
parent | Solve day 3 part 1 (diff) | |
download | aoc-feb34fac48dac79881bff93a2e60e69a08e432a2.tar.gz aoc-feb34fac48dac79881bff93a2e60e69a08e432a2.zip |
Solve day 3 part 2
-rw-r--r-- | 2021/day03.pl | 32 |
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"; |