aoc2021

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

commit 6ab15f4b31aa97d85cee5e75aa8a52a311f7c1c2
parent aea1e9ebf5d71e3f25a82fcea9fc4f4447191d63
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Thu,  9 Dec 2021 00:30:28 +0000

update to get proper solution to Day 05 Part 2

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

diff --git a/day05-2.pl b/day05-2.pl @@ -4,21 +4,14 @@ use strict; use warnings; use v5.22; use List::Util qw( max ); -use diagnostics; sub draw_matrix { my ($matrix) = shift; my $answer; foreach my $y (@$matrix) { foreach my $x (@$y) { - if (defined( $x )) { - print $x; - $answer++ if ($x > 1); - } else { - print "."; - } + $answer++ if (defined( $x) && ($x > 1)); } - print "\n"; } return $answer; } @@ -37,23 +30,26 @@ my @matrix = (); my ($rows, $columns) = (0, 0); foreach (@input) { my ($x1, $y1, $x2, $y2) = ( /(\d+),(\d+) -> (\d+),(\d+)/ ); - say "input is ", join(", ", ($x1, $y1, $x2, $y2)); if ($x1 == $x2) { # line is vertical - say "line is vertical"; ($y1, $y2) = ($y2, $y1) if ($y1 > $y2); # swap so that $y1 < $y2 for (my $y = $y1; $y <= $y2; $y++) { $matrix[$y][$x1]++; } } elsif ($y1 == $y2) { # line is horizontal - say "line is horizontal"; ($x1, $x2) = ($x2, $x1) if ($x1 > $x2); # swap so that $x1 < $x2 for (my $x = $x1; $x <= $x2; $x++) { $matrix[$y1][$x]++; } } - draw_matrix( \@matrix, $rows, $columns); - $wait = <STDIN>; + else { # line is diagonal + my $dx = ($x2 > $x1) ? 1 : -1; + my $dy = ($y2 > $y1) ? 1 : -1; + for (my $x = $x1, my $y = $y1; $x!=$x2 && $y!=$y2; $x+=$dx, $y+=$dy) { + $matrix[$y][$x]++; + } + $matrix[$y2][$x2]++; # for loop above stops just before reaching 2nd point + } } say draw_matrix( \@matrix );