Advertisement
musifter

AoC day 17 (pt2), Perl

Dec 17th, 2020
1,649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.01 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Clone qw(clone);
  7.  
  8. $; = ',';
  9.  
  10. my %Grid;
  11.  
  12. sub init_grid {
  13.     my $dim;
  14.     my $y = 0;
  15.     while (<>) {
  16.         chomp;
  17.         $dim = length $_;
  18.         my $x = 0;
  19.         foreach my $cell (split //) {
  20.             $Grid{0,0,$y,$x} = ($cell eq '#') ? 1 : 0;
  21.             $x++;
  22.         }
  23.         $y++;
  24.     }
  25.  
  26.     for my $w (-1 .. 1) {
  27.         for my $z (-1 .. 1) {
  28.             for my $y (-1 .. $dim) {
  29.                 for my $x (-1 .. $dim) {
  30.                     $Grid{$w,$z,$y,$x} //= 0;
  31.                 }
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. #
  38. # Mainline
  39. #
  40. &init_grid();
  41.  
  42. for my $time (1 .. 6) {
  43.     my %next;
  44.     my $live = 0;
  45.  
  46.     print "Time: $time; ";
  47.     foreach my $coord (keys %Grid) {
  48.         my ($cw, $cz, $cy, $cx) = split( /,/, $coord );
  49.  
  50.         # count neighbours (including self)
  51.         my $neigh = 0;
  52.         foreach my $w ($cw - 1 .. $cw + 1) {
  53.             foreach my $z ($cz - 1 .. $cz + 1) {
  54.                 foreach my $y ($cy - 1 .. $cy + 1) {
  55.                     foreach my $x ($cx - 1 .. $cx + 1) {
  56.                         $neigh++ if ($Grid{$w,$z,$y,$x});
  57.                     }
  58.                 }
  59.             }
  60.         }
  61.  
  62.         # check live (remember to add one to self-live checks
  63.         if ($Grid{$coord}) {
  64.             $next{$coord} = ($neigh == 3 || $neigh == 4) ? 1 : 0;
  65.         } else {
  66.             $next{$coord} = ($neigh == 3) ? 1 : 0;
  67.         }
  68.  
  69.         # count live cells and make neighbours exist to check next time
  70.         if ($next{$coord}) {
  71.             $live++;
  72.             foreach my $w ($cw - 1 .. $cw + 1) {
  73.                 foreach my $z ($cz - 1 .. $cz + 1) {
  74.                     foreach my $y ($cy - 1 .. $cy + 1) {
  75.                         foreach my $x ($cx - 1 .. $cx + 1) {
  76.                             $next{$w,$z,$y,$x} //= 0;
  77.                         }
  78.                     }
  79.                 }
  80.             }
  81.         }
  82.     }
  83.  
  84.     print "live: $live\n";
  85.     %Grid = %{clone(\%next)};
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement