aoc2021

Advent of Code 2021 solutions in Perl.
git clone git://git.samirparikh.com/aoc2021
Log | Files | Refs | README

commit e778587dd58d65a19d1efe8068bbbfe1a7749bf6
parent f45642928b8e57f47586249d48ce0315ac574da0
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Sat,  4 Dec 2021 13:07:50 +0000

refactor Day 03 Part 1 solution to make it easier to understand

Diffstat:
Mday03-1.pl | 22+++++++++-------------
1 file changed, 9 insertions(+), 13 deletions(-)

diff --git a/day03-1.pl b/day03-1.pl @@ -16,27 +16,23 @@ chomp( my @input = ( <$filehandle> ) ); # Part 1 my $len = length($input[0]) - 1; # number of bits - 1 -my %count_0 = (); -my %count_1 = (); my $gamma_rate = ""; my $epsilon_rate = ""; -foreach (@input) { - my @diagnostic = split //; - for (0 .. $len) { - if ($diagnostic[$_]) { # bit at position $_ is 1 - $count_1{$_}++; +foreach my $index (0 .. $len) { # first iterate through indices... + my $count; + foreach my $line (@input) { # ...and then through the numbers/lines + if ( (split //, $line)[$index] ) { # if bit at position $index is 1 + $count++; # postive or zero count means 1 } else { - $count_0{$_}++; + $count--; # negative count means 0 } } -} - -for (0 .. $len) { # find which bit occurs the most at each position - if ($count_0{$_} > $count_1{$_}) { + # now see which is the most common bit at the index + if ($count < 0) { # most common bit at index is 0 $gamma_rate .= "0"; $epsilon_rate .= "1"; - } else { + } else { # most common bit at index is 1 $gamma_rate .= "1"; $epsilon_rate .= "0"; }