aoc2021

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

day07-2.pl (1044B) - raw


      1 #!/usr/bin/env perl
      2 
      3 use strict;
      4 use warnings;
      5 use v5.22;
      6 use List::Util qw( min max );
      7 
      8 sub get_filehandle {
      9     if (@ARGV !=1) {
     10         die "Usage: $0 [input-filename]";
     11     }
     12     my $input_filename = $ARGV[0];
     13     open my $filehandle, '<', $input_filename or
     14         die "Could not open input file $input_filename: $!";
     15     return $filehandle;
     16 }
     17 
     18 sub get_numbers {
     19     my $fh = shift;
     20     chomp( my $numbers = ( <$fh> ) );
     21     return (split( ",", $numbers));
     22 }
     23 
     24 # Advent of Code 2021 Day 07
     25 my $filehandle  = get_filehandle();
     26 my @numbers     = get_numbers($filehandle);
     27 my $min_fuel_cost;
     28 my $horiz_pos;
     29 my $low = min(@numbers);
     30 my $high = max(@numbers);
     31 
     32 foreach my $x ($low .. $high) {
     33     my $fuel_cost = 0;
     34     foreach my $y (0 .. $#numbers) {
     35         my $n = abs($x - $numbers[$y]);
     36         $fuel_cost += $n * ($n + 1) / 2;
     37     }
     38     if (!defined($min_fuel_cost) || $fuel_cost < $min_fuel_cost) {
     39         $min_fuel_cost = $fuel_cost;
     40         $horiz_pos = $x;
     41     }
     42 }
     43 
     44 say "winning position is $horiz_pos with cost of $min_fuel_cost";