From 81d7b11934be0f57efd2021793730ebe6f522ac2 Mon Sep 17 00:00:00 2001 From: June McEnroe Date: Fri, 3 Dec 2021 10:57:38 -0500 Subject: Refactor day 3 using grep to count ones C has turned my brain to for-loop goop. --- 2021/day03.pl | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to '2021') 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--; } -- cgit 1.4.1