aoc2015

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

Day13.pm (1137B) - raw


      1 package Day13;
      2 
      3 use strict;
      4 use warnings;
      5 use v5.32;
      6 use Exporter qw( import );
      7 use List::Util qw( max );
      8 use Algorithm::Permute;
      9 
     10 our @EXPORT = qw( calc_tot_hap_chg );
     11 
     12 sub calc_tot_hap_chg {
     13     my @answers;
     14     my @people    = @{ $_[0] };
     15     my %hap_units = %{ $_[1] };
     16     Algorithm::Permute::permute {
     17         # since we are already iterating on @people, it is a read-only variable
     18         # within this loop and thus we cannot unshift or push on it.  Therefore,
     19         # we have to copy it into a new variable, @seat_assign
     20         my @seat_assign = @people;
     21         my $hap_change = 0;
     22         unshift @seat_assign => $seat_assign[ -1 ];
     23         push @seat_assign    => $seat_assign[ 1 ];
     24         foreach my $position ( 1 .. scalar @people ) {
     25             my $person   = $seat_assign[ $position ];
     26             my $left     = $seat_assign[ $position - 1 ];
     27             my $right    = $seat_assign[ $position + 1 ];
     28             $hap_change += $hap_units{ $person }{ $left };
     29             $hap_change += $hap_units{ $person }{ $right };
     30         }
     31         push @answers => $hap_change;
     32     } @people;
     33 
     34     return max @answers;
     35 }
     36 
     37 1;