Advertisement
musifter

AoC 2022 day 5 (Perl)

Dec 5th, 2022
2,025
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.98 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.32;
  4. use warnings;
  5.  
  6. $/ = '';
  7.  
  8. # Snarf sections
  9. my @section = map {[split /\n/]} <>;
  10.  
  11. # grab last line of first section and build (pos -> name) key map for the stacks
  12. my %key;
  13. $_ = pop( $section[0]->@* );
  14. $key{pos() - 1} = $1  while (m#(\w)#g);
  15.  
  16. # Use rest of section one to build initial stacks
  17. my %stack;
  18. foreach my $line ($section[0]->@*) {
  19.     # Check each position for a crate and stack if found
  20.     foreach my $pos (keys %key) {
  21.         my $crate = substr( $line, $pos, 1 );
  22.         push( $stack{$key{$pos}}->@*, $crate ) if ($crate ne ' ');
  23.     }
  24. }
  25.  
  26. # Execute commands from second section
  27. foreach my $cmd ($section[1]->@*) {
  28.     my ($num, $src, $dst) = ($cmd =~ m#move (\d+) from (.) to (.)#);
  29.  
  30.     # Remove reverse for part two:
  31.     unshift( $stack{$dst}->@*, reverse splice( $stack{$src}->@*, 0, $num ) );
  32. }
  33.  
  34. # First crate from the stacks in the order keys were listed:
  35. say "Part 1: ", map { $stack{$key{$_}}[0] } sort {$a <=> $b} keys %key;
  36.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement