Advertisement
musifter

AoC 2024 day 15, part 1 (Perl)

Dec 15th, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.34 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7.  
  8. use Math::Vector::Real;
  9.  
  10. my ($vy,$vx) = Math::Vector::Real->canonical_base(2);
  11. my %Dirs = ('v' => $vy, '>' => $vx, '^' => -$vy, '<' => -$vx);
  12.  
  13. $/ = '';
  14. my ($in_map, $in_moves) = map {[split /\n/]} <>;
  15.  
  16. my @moves = map {  split //  } @$in_moves;
  17. my @Grid  = map { [split //] } @$in_map;
  18.  
  19. sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
  20.  
  21. my $robot;
  22. foreach my $y (0 .. $in_map->$#*) {
  23.     if ($in_map->[$y] =~ m#@#) {
  24.         $robot = V($y, $-[0]);
  25.         $Grid[$y][$-[0]] = '.';
  26.         last;
  27.     }
  28. }
  29.  
  30. MOVE:
  31. foreach my $d (@moves) {
  32.     my $move = $robot + $Dirs{$d};
  33.     my $targ = grid_at($move);
  34.  
  35.     if ($targ ne 'O') {
  36.         $robot = $move  if ($targ eq '.');  # move
  37.         next MOVE;
  38.     }
  39.  
  40.     # Pushing a box
  41.     my $end = $move;
  42.     $end += $Dirs{$d}  while (grid_at($end) eq 'O');    # multipush
  43.  
  44.     next MOVE if (grid_at($end) eq '#');    # bump
  45.  
  46.     # Put box at empty end, clear front of push, move robot to it.
  47.     $Grid[  $end->[0] ][  $end->[1] ] = 'O';
  48.     $Grid[ $move->[0] ][ $move->[1] ] = '.';
  49.     $robot = $move;
  50. }
  51.  
  52. my $part1 = 0;
  53. foreach my $y (0 .. $#Grid) {
  54.     foreach my $x (0 .. $Grid[0]->$#*) {
  55.         $part1 += (100 * $y + $x)  if ($Grid[$y][$x] eq 'O');
  56.     }
  57. }
  58.  
  59. say "Part 1: $part1";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement