aoc2021

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

day07-1.pl (935B) - raw


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