commit 78973c0984220bb945912faf993edf0f149c359d
parent f11534a75a5ead557232193fb7518f1139c3ef54
Author: Samir Parikh <noreply@samirparikh.com>
Date: Sat, 5 Nov 2022 15:28:26 +0000
refactor solution to part 1 of day13
Diffstat:
2 files changed, 40 insertions(+), 23 deletions(-)
diff --git a/day13/Day13.pm b/day13/Day13.pm
@@ -0,0 +1,37 @@
+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 );
+my @answers;
+
+sub calc_tot_hap_chg {
+ 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;
diff --git a/day13/day13.pl b/day13/day13.pl
@@ -4,15 +4,14 @@
use strict;
use warnings;
use v5.32;
-use List::Util qw( max );
-use Algorithm::Permute;
+use lib '.';
+use Day13 qw( calc_tot_hap_chg );
@ARGV = "input" unless @ARGV;
chomp( my $input = do { local $/; <> } );
my @deltas = split /\n/, $input;
my %people;
my %hap_units;
-my @answers;
foreach ( @deltas ) {
my ( $person, $gain_lose, $units, $neighbor ) =
@@ -23,24 +22,5 @@ foreach ( @deltas ) {
my @people = sort keys %people;
-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;
-
-
-say "part 1: ", max @answers;
+say "part 1: ", calc_tot_hap_chg( \@people, \%hap_units );
#say "part 2: ";