diff options
Diffstat (limited to '')
-rw-r--r-- | 2021/day03.pl | 14 |
1 files changed, 5 insertions, 9 deletions
diff --git a/2021/day03.pl b/2021/day03.pl index 7e8d2fc..cd8b1db 100644 --- a/2021/day03.pl +++ b/2021/day03.pl @@ -6,31 +6,27 @@ while (<>) { $bits = length($_); push @nums, oct("0b".$_); } -sub countOnes { +sub moreOnes { my $i = shift; - my $ones = 0; - foreach (@_) { - $ones++ if $_ & (1 << $i); - } - $ones; + (grep { $_ & (1 << $i) } @_) >= @_ / 2; } my $gamma = 0; for (my $i = 0; $i < $bits; $i++) { - $gamma |= 1 << $i if countOnes($i, @nums) > @nums / 2; + $gamma |= 1 << $i if moreOnes($i, @nums); } 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; + my $most = moreOnes($i, @o2) << $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; + my $least = !moreOnes($i, @co2) << $i; @co2 = grep { ($_ & (1 << $i)) == $least } @co2; $i--; } |