aoc2021

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

commit 77472dacbfefdef120a61b469fbe5849d7558f86
parent 685fbd8e10248f7bf98b0b64868eca839d8b2282
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Fri, 17 Dec 2021 20:58:09 +0000

update day07-2.pl with notes about what I still need to do and correct

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

diff --git a/day07-2.pl b/day07-2.pl @@ -0,0 +1,52 @@ +#!/usr/bin/env perl + +# i am doing this wrong +# I am assuming that the only positions they crabs can align on are ones +# that they already occupy. I got luck with Part 1 in that one of the crabs +# already occupied the winning answer +# for Part 2, it's possible that the winning position that consumes the least +# amoutn of fuel is a position that no crab initially occupies +# I need to find the range of positions (min/max) and use that as the ranges +# for the x and y loops +use strict; +use warnings; +use v5.22; + +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 $min_fuel_cost; +my $horiz_pos; + +foreach my $x (0 .. $#numbers) { + my $fuel_cost = 0; + foreach my $y (0 .. $#numbers) { + my $n = abs($numbers[$x] - $numbers[$y]); + $fuel_cost += $n * ($n + 1) / 2; + say "move from $numbers[$y] to $numbers[$x]: $n"; + } + say "------------"; + if (!defined($min_fuel_cost) || $fuel_cost < $min_fuel_cost) { + $min_fuel_cost = $fuel_cost; + $horiz_pos = $x; + } + say "TOTAL cost to move to position $x is $fuel_cost"; +} + +say "winning position is $horiz_pos with cost of $min_fuel_cost";