aoc2021

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

commit 928d2685b89788eb2f61823608fb015c0afdf13f
parent 77472dacbfefdef120a61b469fbe5849d7558f86
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Fri, 17 Dec 2021 22:23:45 +0000

update day07-2.pl to provide proper solution for Day 07 Part 2

Diffstat:
Mday07-2.pl | 18+++++-------------
1 file changed, 5 insertions(+), 13 deletions(-)

diff --git a/day07-2.pl b/day07-2.pl @@ -1,16 +1,9 @@ #!/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; +use List::Util qw( min max ); sub get_filehandle { if (@ARGV !=1) { @@ -33,20 +26,19 @@ my $filehandle = get_filehandle(); my @numbers = get_numbers($filehandle); my $min_fuel_cost; my $horiz_pos; +my $low = min(@numbers); +my $high = max(@numbers); -foreach my $x (0 .. $#numbers) { +foreach my $x ($low .. $high) { my $fuel_cost = 0; foreach my $y (0 .. $#numbers) { - my $n = abs($numbers[$x] - $numbers[$y]); + my $n = abs($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";