Advertisement
musifter

AoC 2023, day 21 (Perl)

Dec 21st, 2023 (edited)
1,270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.24 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature             qw(say);
  7. use Math::Polynomial;
  8.  
  9. $| = 1;
  10.  
  11. my $TARGET = 26501365;
  12. my @Grid = map { chomp; [split(//)] } <>;
  13. my @Dirs = ([1,0], [0,1], [-1,0], [0,-1]);
  14.  
  15. sub print_grid  { say join( '', @$_ ) foreach (@Grid); }
  16.  
  17. # Assume square grid, and start in middle:
  18. my $size = scalar( @Grid );
  19. my @pos  = (int($size / 2), int($size / 2));
  20.  
  21. die "S not in middle"  if ($Grid[$pos[0]][$pos[1]] ne 'S');
  22.  
  23. my @steps = (0);
  24. my %curr = (join( $;, @pos ) => 1);
  25. foreach my $time (1 .. ($TARGET % $size) + 2 * $size) {
  26.     my %next;
  27.     print ::stderr "$time\r";
  28.     foreach my $l (keys %curr) {
  29.         my @pt = split( $;, $l );
  30.         foreach my $d (@Dirs) {
  31.             my $ny = $pt[0] + $d->[0];
  32.             my $nx = $pt[1] + $d->[1];
  33.             $next{$ny,$nx}++  if ($Grid[$ny % $size][$nx % $size] ne '#');
  34.         }
  35.     }
  36.  
  37.     %curr = %next;
  38.  
  39.     push( @steps, scalar keys %curr );
  40.     say "Part 1: $steps[-1]"  if ($time == 64);
  41. }
  42.  
  43. my @x = map {$TARGET % $size + $_ * $size} (0, 1, 2);
  44. my $fact = $size * $size;
  45.  
  46. my $f = Math::Polynomial->interpolate( \@x, [map{$fact * $steps[$_]} @x] );
  47.  
  48. say "f(x) = $f / ", $fact;
  49. say "Part 2: ", $f->evaluate( $TARGET ) / $fact;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement