package Day13; use strict; use warnings; use v5.32; use Exporter qw( import ); use List::Util qw( max ); use Algorithm::Permute; our @EXPORT = qw( calc_tot_hap_chg ); sub calc_tot_hap_chg { my @answers; my @people = @{ $_[0] }; my %hap_units = %{ $_[1] }; Algorithm::Permute::permute { # since we are already iterating on @people, it is a read-only variable # within this loop and thus we cannot unshift or push on it. Therefore, # we have to copy it into a new variable, @seat_assign my @seat_assign = @people; my $hap_change = 0; unshift @seat_assign => $seat_assign[ -1 ]; push @seat_assign => $seat_assign[ 1 ]; foreach my $position ( 1 .. scalar @people ) { my $person = $seat_assign[ $position ]; my $left = $seat_assign[ $position - 1 ]; my $right = $seat_assign[ $position + 1 ]; $hap_change += $hap_units{ $person }{ $left }; $hap_change += $hap_units{ $person }{ $right }; } push @answers => $hap_change; } @people; return max @answers; } 1;