day02.pl (951B) - raw
1 #!/usr/bin/env perl 2 3 use strict; 4 use warnings; 5 use v5.22; 6 7 if (@ARGV !=1) { 8 die "Usage: $0 [input-filename]"; 9 } 10 11 my $input_filename = $ARGV[0]; 12 open my $filehandle, '<', $input_filename or 13 die "Could not open input file $input_filename: $!"; 14 15 chomp( my @input = ( <$filehandle> ) ); 16 17 # Part 1 18 my ($horizontal, $depth); 19 20 foreach (@input) { 21 my ($direction, $distance) = split; 22 $horizontal += $distance if ($direction eq 'forward'); 23 $depth += $distance if ($direction eq 'down'); 24 $depth -= $distance if ($direction eq 'up'); 25 } 26 27 say $horizontal * $depth; 28 29 # Part 2 30 ($horizontal, $depth) = (0, 0); 31 my $aim = 0; 32 33 foreach (@input) { 34 my ($direction, $distance) = split; 35 if ($direction eq 'forward') { 36 $horizontal += $distance; 37 $depth += $aim * $distance; 38 } 39 $aim += $distance if ($direction eq 'down'); 40 $aim -= $distance if ($direction eq 'up'); 41 } 42 43 say $horizontal * $depth;