Advertisement
musifter

AoC day 11, part 2

Dec 11th, 2020
1,222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.88 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. $| = 1;
  7.  
  8. my @DIRS = ([-1,-1], [-1,0], [-1,1], [ 0,-1], [ 0,1], [ 1,-1], [ 1,0], [ 1,1]);
  9.  
  10. # Read Grid into buffer adding spaces for quick and easy boundary handling
  11. # Grid[ buffer ][ ycoord ][ xcoord ]
  12. my @Grid = [map { chomp; [' ', split(//), ' '] } <>];
  13. my $X_SIZE = @{$Grid[0][0]};
  14.  
  15. # borders for the top and bottom
  16. unshift( @{$Grid[0]}, [(' ') x $X_SIZE] );
  17. push(    @{$Grid[0]}, [(' ') x $X_SIZE] );
  18. my $Y_SIZE = @{$Grid[0]};
  19.  
  20. # initialize other buffer
  21. $Grid[1] = [ map { [(' ') x $X_SIZE] } (0 .. $Y_SIZE) ];
  22.  
  23. # for swapping between old and new buffers
  24. my ($old, $new) = (0, 1);
  25.  
  26. # Return count of adjacent occupied squares
  27. sub get_occupied {
  28.     my ($y, $x) = @_;
  29.  
  30.     my $ret = 0;
  31.     foreach my $d (@DIRS) {
  32.         my ($ny, $nx) = ($y + $d->[0], $x + $d->[1]);
  33.         while ($Grid[$old][$ny][$nx] eq '.') {
  34.             ($ny, $nx) = ($ny + $d->[0], $nx + $d->[1]);
  35.         }
  36.  
  37.         $ret += ($Grid[$old][$ny][$nx] eq '#');
  38.     }
  39.  
  40.     return ($ret);
  41. }
  42.  
  43. #
  44. # Main loop
  45. #
  46. my ($gen, $changes, $total_occ) = (0,1,0);
  47. while ($changes) {
  48.     ($changes, $total_occ) = (0,0);
  49.     for (my $y = 1; $y < $Y_SIZE - 1; $y++) {
  50.         for (my $x = 1; $x < $X_SIZE - 1; $x++) {
  51.             my $occ = &get_occupied( $y, $x );
  52.  
  53.             if ($Grid[$old][$y][$x] eq 'L' && $occ == 0) {
  54.                 $Grid[$new][$y][$x] = '#';
  55.                 $changes++;
  56.             } elsif ($Grid[$old][$y][$x] eq '#' && $occ >= 5) {
  57.                 $Grid[$new][$y][$x] = 'L';
  58.                 $changes++;
  59.             } else {
  60.                 $Grid[$new][$y][$x] = $Grid[$old][$y][$x];
  61.             }
  62.  
  63.             $total_occ += ($Grid[$new][$y][$x] eq '#');
  64.         }
  65.     }
  66.  
  67.     printf( "Generation: %4d  Occupied: %4d  Changes: %4d\r",
  68.                 ++$gen, $total_occ, $changes );
  69.  
  70.     ($old, $new) = ($new, $old);
  71. }
  72.  
  73. print "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement