day05-1.pl (1141B) - raw
1 #!/usr/bin/env perl 2 3 use strict; 4 use warnings; 5 use v5.22; 6 use List::Util qw( max ); 7 use diagnostics; 8 9 sub draw_matrix { 10 my ($matrix) = shift; 11 my $answer; 12 foreach my $y (@$matrix) { 13 foreach my $x (@$y) { 14 $answer++ if (defined( $x ) && ($x > 1)); 15 } 16 } 17 return $answer; 18 } 19 20 if (@ARGV !=1) { 21 die "Usage: $0 [input-filename]"; 22 } 23 24 my $input_filename = $ARGV[0]; 25 open my $filehandle, '<', $input_filename or 26 die "Could not open input file $input_filename: $!"; 27 28 chomp( my @input = ( <$filehandle> ) ); 29 my $wait; 30 my @matrix = (); 31 my ($rows, $columns) = (0, 0); 32 foreach (@input) { 33 my ($x1, $y1, $x2, $y2) = ( /(\d+),(\d+) -> (\d+),(\d+)/ ); 34 if ($x1 == $x2) { # line is vertical 35 ($y1, $y2) = ($y2, $y1) if ($y1 > $y2); # swap so that $y1 < $y2 36 for (my $y = $y1; $y <= $y2; $y++) { 37 $matrix[$y][$x1]++; 38 } 39 } 40 elsif ($y1 == $y2) { # line is horizontal 41 ($x1, $x2) = ($x2, $x1) if ($x1 > $x2); # swap so that $x1 < $x2 42 for (my $x = $x1; $x <= $x2; $x++) { 43 $matrix[$y1][$x]++; 44 } 45 } 46 } 47 48 say draw_matrix( \@matrix );