aoc2021

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

commit 928681c5620df9a2de3f1a0fed1024aa95f71f18
parent 49c31ebe095dc84293967ecf7c7cfeb7c1eb4908
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Fri, 17 Dec 2021 20:40:33 +0000

initial commit for day07-1.pl

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

diff --git a/day07-1.pl b/day07-1.pl @@ -0,0 +1,53 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use v5.22; +use List::Util qw(sum); + +sub get_filehandle { + 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: $!"; + return $filehandle; +} + +sub get_numbers { + my $fh = shift; + chomp( my $numbers = ( <$fh> ) ); + return (split( ",", $numbers)); +} + +# Advent of Code 2021 Day 07 +my $filehandle = get_filehandle(); +my @numbers = get_numbers($filehandle); +#my $num_crabs = scalar(@numbers); +my $min_fuel_cost; +my $horiz_pos; +#say "@numbers"; + +#if (defined($fuel_cost)) { +# say "it's defined"; +#} else { +# say "it's NOT defined"; +#} + +#say $num_crabs; + +foreach my $x (0 .. $#numbers) { + my $fuel_cost; + foreach my $y (0 .. $#numbers) { + $fuel_cost += abs($numbers[$x] - $numbers[$y]); + } + say $x; + if ($fuel_cost < $min_fuel_cost || !defined($min_fuel_cost)) { + $min_fuel_cost = $fuel_cost; + $horiz_pos = $x; + say "we have new winning position $x with fuel cost $fuel_cost"; + } +} + +say "winning position is $horiz_pos with cost of $min_fuel_cost";