aoc2021

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

commit e5367db8ec720660c278cfa1f7477abf8be53556
parent 29def93e15cbb7f699974fe974a4fbd5e6614d9f
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Thu,  2 Dec 2021 14:09:42 +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;