Advertisement
musifter

AoC 2021 day 20 (Perl)

Dec 20th, 2021 (edited)
1,658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.41 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils   qw(sum);
  7. use Math::BigInt;
  8.  
  9. $| = 1;
  10. $; = ',';
  11.  
  12. my @Dirs = ([-1,-1], [-1, 0], [-1, 1],
  13.             [ 0,-1], [ 0, 0], [ 0, 1],
  14.             [ 1,-1], [ 1, 0], [ 1, 1]);
  15.  
  16. # Read in cellular automata rules:
  17. $_ = <>;
  18. chomp;
  19. my @Map = map { int($_ eq '#') } split //;
  20.  
  21. # Read in starting state:
  22. $_ = <>;    # blank line
  23. my @Input = map { chomp; [map {int($_ eq '#')} split //] } <>;
  24.  
  25. my $MAX_Y = $#Input;
  26. my $MAX_X = $Input[0]->$#*;
  27.  
  28. # State of all points outside the bounding box
  29. my $Border = 0;
  30.  
  31. # Load starting position into Grid:
  32. my %Grid;
  33. foreach my $y (0 .. $MAX_Y) {
  34.     foreach my $x (0 .. $MAX_X) {
  35.         $Grid{$y,$x} = $Input[$y][$x];
  36.     }
  37. }
  38.  
  39. sub pixel_count {
  40.     return ($Border ? Math::BigInt->binf() : sum map { $Grid{$_} } keys %Grid);
  41. }
  42.  
  43. foreach my $t (1 .. 50) {
  44.     print ::stderr "Time: $t\r";
  45.  
  46.     my %next;
  47.     foreach my $y (-$t .. $MAX_Y + $t) {
  48.         foreach my $x (-$t .. $MAX_X + $t) {
  49.             my $idx = 0;
  50.             foreach my $neigh (map {[$y + $_->[0], $x + $_->[1]]} @Dirs) {
  51.                 $idx = 2 * $idx + ($Grid{ join($;, @$neigh) } // $Border);
  52.             }
  53.  
  54.             $next{$y,$x} = $Map[$idx];
  55.         }
  56.     }
  57.  
  58.     %Grid = %next;
  59.     $Border = $Map[511 * $Border];
  60.  
  61.     print( "\nPart 1: ", &pixel_count, "\n" ) if ($t == 2);
  62. }
  63.  
  64. print( "\nPart 2: ", &pixel_count, "\n" );
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement