package Part1; use 5.36.0; our @ISA = 'Exporter'; our @EXPORT_OK = qw/ part1 $sample /; use Path::Tiny; our $sample = path('./sample')->slurp; sub parse_heaps($heaps) { my( $header, @crates ) = reverse split "\n", $heaps; my @stacks; while( $header !~ /^\s*$/ ) { $header =~ s/^(\s+)\d//; my $n = length $1; @crates = map { no warnings; substr $_, $n } @crates; my @stack = grep { /\w/ } map { no warnings; s/(.)//; $1 } @crates; push @stacks, \@stack; } return @stacks; } sub parse_commands($text) { return map { [/\d+/g] } split "\n", $text } sub move_stacks($stacks, $commands) { for my $command ( @$commands ) { for( 1..$command->[0] ) { push $stacks->[$command->[2] - 1]->@*, pop $stacks->[$command->[1]- 1]->@*; } } return @$stacks; } sub part1($text) { my( $heaps, $commands ) = split "\n\n", $text; my @heaps = parse_heaps($heaps); my @commands = parse_commands($commands); my @stacks = move_stacks( \@heaps, \@commands ); return join '', map { pop @$_ } @stacks; } 1;