From feb34fac48dac79881bff93a2e60e69a08e432a2 Mon Sep 17 00:00:00 2001 From: June McEnroe Date: Fri, 3 Dec 2021 10:29:58 -0500 Subject: Solve day 3 part 2 --- 2021/day03.pl | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) (limited to '2021/day03.pl') 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"; -- cgit 1.4.1 216a65a&follow=1'>diff homepage
path: root/2016 (unfollow)
Commit message (Collapse)Author
2020-11-22Day 1, part 2June McEnroe
2020-11-22Day 1June McEnroe
2020-11-22Move to 2016 directoryJune McEnroe