aoc2021

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

commit 7fe940345556c6727443df409e20d4005e7fb322
parent 9f929507996da7d9f63427f9f5f2c4a0cb213d54
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Thu,  2 Dec 2021 14:09:35 +0000

add Day 02 solutions

Diffstat:
Aday02.pl | 43+++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+), 0 deletions(-)

diff --git a/day02.pl b/day02.pl @@ -0,0 +1,43 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use v5.22; + +if (@ARGV !=1) { + die "Usage: $0 [input-filename]"; +} + +my $input_filename = $ARGV[0]; +open my $filehandle, '<', $input_filename or + die "Could not open input file $input_filename: $!"; + +chomp( my @input = ( <$filehandle> ) ); + +# Part 1 +my ($horizontal, $depth); + +foreach (@input) { + my ($direction, $distance) = split; + $horizontal += $distance if ($direction eq 'forward'); + $depth += $distance if ($direction eq 'down'); + $depth -= $distance if ($direction eq 'up'); +} + +say $horizontal * $depth; + +# Part 2 +($horizontal, $depth) = (0, 0); +my $aim = 0; + +foreach (@input) { + my ($direction, $distance) = split; + if ($direction eq 'forward') { + $horizontal += $distance; + $depth += $aim * $distance; + } + $aim += $distance if ($direction eq 'down'); + $aim -= $distance if ($direction eq 'up'); +} + +say $horizontal * $depth;