#!/usr/bin/env perl 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; foreach my $y (0 .. $#numbers) { $fuel_cost += abs($numbers[$x] - $numbers[$y]); } 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";