aoc2021

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

commit ee74ace205e37586ff7985753f7f1bdf8fccf5b2
parent e37d98bd6da6cacb94d183c5f6480b837bc5fe7a
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Mon,  6 Dec 2021 15:32:07 +0000

update comments

Diffstat:
Mday04-1.pl | 45++++++++++++++++-----------------------------
1 file changed, 16 insertions(+), 29 deletions(-)

diff --git a/day04-1.pl b/day04-1.pl @@ -86,58 +86,38 @@ sub print_board_state { sub check_for_winner { my ($boards, $state) = @_; #my $found_winner = 0; - # check for row wins +# check for row wins foreach my $board (@$boards) { # $board is ref to board array foreach my $row (@$board) { # $row is ref to board row array my $total = 0; - foreach my $column (@$row) { + foreach my $column (@$row) { # $column is the actual value of + # the number in @$row $total += $state->{$board}{$row}{$column}; } if ($total == 5) { say "found row winner"; #$found_winner = 1; - return 1; - } - } - foreach (0 .. 4) { - foreach my $row (@$boards) { - say @{${$row}[$_]}; + return $board; } } +# for each board, iterate through each column (0 .. 4) foreach (0 .. 4) { my $total = 0; foreach my $row (@$board) { - #say "$board\t$_\t$row->[$_]\t$state->{$board}{$row}{$row->[$_]}"; +# here, $_ represents the index within the array @$row. Because the hash key +# stores the actual value, we need to deference $row (which is an array +# reference) and then look up the value stored in the index $_ $total += $state->{$board}{$row}{$row->[$_]}; } if ($total == 5) { say "found column winner"; - return 1; + return $board; } } } return 0; # no winner found } -sub check_for_horiz_winner { - my ($boards, $state) = @_; - foreach my $board (@$boards) { # $board is ref to board array - foreach (0 .. 4) { - foreach my $row (@$board) { - say "$board\t$_\t$row->[$_]\t$state->{$board}{$row}{$row->[$_]}"; - } - } - #foreach my $row (@$board) { # $row is ref to board row array -# foreach my $column (@$row) { -# say "$board\t$row\t$column"; -# } -# foreach (0 .. 4) { -# say "$board\t$row\t$row->[$_]"; -# } - #} - } -} - # Advent of Code 2021 Day 04 Part 1 # initialize game variables my $filehandle = get_filehandle(); @@ -145,6 +125,11 @@ my @numbers = get_numbers($filehandle); my @boards = initialize_boards($filehandle); my %state = initialize_state(\@boards); my $turn = 0; + +# $winner_found plays double duty. When equal to 0, it means that +# we haven't yet found a winning board. When we do, the subroutine +# check_for_winner returns a reference to the array of the winning +# board which we can then submit to calculate_score. my $winner_found = 0; until ($winner_found) { @@ -157,6 +142,8 @@ until ($winner_found) { last; } } + +say "\$winner_found = $winner_found"; #check_for_horiz_winner(\@boards, \%state); print_board_state(\@boards, \%state);