diff options
author | June McEnroe <june@causal.agency> | 2021-12-03 10:57:38 -0500 |
---|---|---|
committer | June McEnroe <june@causal.agency> | 2021-12-03 10:57:38 -0500 |
commit | 81d7b11934be0f57efd2021793730ebe6f522ac2 (patch) | |
tree | 34703706cfddffb59f081b07f3fb5ebd80cbda11 | |
parent | Solve day 3 part 2 (diff) | |
download | aoc-81d7b11934be0f57efd2021793730ebe6f522ac2.tar.gz aoc-81d7b11934be0f57efd2021793730ebe6f522ac2.zip |
Refactor day 3 using grep to count ones
C has turned my brain to for-loop goop.
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--; } |