#!/usr/bin/env perl use strict; use warnings; use v5.22; use List::Util qw( min max ); 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; my $low = min(@numbers); my $high = max(@numbers); foreach my $x ($low .. $high) { my $fuel_cost = 0; foreach my $y (0 .. $#numbers) { my $n = abs($x - $numbers[$y]); $fuel_cost += $n * ($n + 1) / 2; } if (!defined($min_fuel_cost) || $fuel_cost < $min_fuel_cost) { $min_fuel_cost = $fuel_cost; $horiz_pos = $x; } } say "winning position is $horiz_pos with cost of $min_fuel_cost";