Advertisement
musifter

AoC 2024, day 18, part 1 (Perl)

Dec 17th, 2024 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.13 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 constant GRID_SIZE => 7;
  9. #use constant TIME => 12;
  10. use constant GRID_SIZE => 71;
  11. use constant TIME => 1024;
  12.  
  13. use Math::Vector::Real;
  14.  
  15. my ($vy,$vx) = Math::Vector::Real->canonical_base(2);
  16. my @Dirs = ($vy, $vx, -$vy, -$vx);
  17.  
  18. # Make grid, adding sentinel ~s to right and bottom
  19. my @Grid = map { [('.') x GRID_SIZE, '~'] } (1 .. GRID_SIZE);
  20. push( @Grid, [('~') x GRID_SIZE] );
  21.  
  22. sub grid_at ($) { my $p = shift; return ($Grid[$p->[1]][$p->[0]]) }
  23. sub print_grid  { say "\t", join( '', @$_ ) foreach (@Grid); }
  24.  
  25. # Read list of points:
  26. my @input = map { V(split /,/) } <>;
  27.  
  28. # Drop up to TIME
  29. $Grid[$_->[1]][$_->[0]] = '#'  foreach (splice( @input, 0, TIME ));
  30.  
  31. my %visit;
  32. my @queue = ([V(0,0), 0]);
  33. my $end   = V(GRID_SIZE - 1, GRID_SIZE - 1);
  34.  
  35. while (my $state = shift @queue) {
  36.     my ($pos, $time) = @$state;
  37.  
  38.     if ($pos == $end) {
  39.         say "Part 1: $time";
  40.         last;
  41.     }
  42.  
  43.     next if ($visit{$pos}++);
  44.  
  45.     # Add legal moves to queue
  46.     push(@queue, [$_, $time + 1]) foreach (grep {grid_at($_) eq '.'} map {$pos + $_} @Dirs);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement