Advertisement
musifter

AoC day11 (Perl)

Dec 10th, 2021
1,758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.30 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(pairwise);
  7.  
  8. $; = ',';
  9.  
  10. my @Dirs = ([-1,-1], [-1, 0], [-1, 1],
  11.             [ 0,-1],          [ 0, 1],
  12.             [ 1,-1], [ 1, 0], [ 1, 1]);
  13.  
  14.  
  15. sub neighbours (\@) {
  16.     my $pos = shift;
  17.  
  18.     my @res = map { [pairwise { $a + $b } @$pos, @$_] } @Dirs;
  19.     return( grep { (0 <= $_->[0] <= 9) && (0 <= $_->[1] <= 9) } @res );
  20. }
  21.  
  22. my @Grid = map { chomp; [split //] } <>;
  23. my @Gridpts = map { my $y = $_; map { [$y,$_] } (0 .. 9) } (0 .. 9);
  24.  
  25. my $flashes = 0;
  26.  
  27. for (my $t = 1; ; $t++) {
  28.     my %flashed;
  29.     my @queue;
  30.  
  31.     # initial flashes
  32.     foreach my $pt (@Gridpts) {
  33.         push( @queue, $pt )  if (++$Grid[$pt->[0]][$pt->[1]] > 9);
  34.     }
  35.  
  36.     # cascade with work queue
  37.     while (my $pos = shift @queue) {
  38.         next if (++$flashed{$pos->[0],$pos->[1]} > 1);
  39.  
  40.         foreach my $n (&neighbours( $pos )) {
  41.             push( @queue, $n )  if (++$Grid[$n->[0]][$n->[1]] > 9);
  42.         }
  43.     }
  44.  
  45.     # discharge flashers
  46.     $flashes += keys %flashed;
  47.     foreach my $f (keys %flashed) {
  48.         my ($y,$x) = split( /,/, $f );
  49.         $Grid[$y][$x] = 0;
  50.     }
  51.  
  52.     if ($t == 100) {
  53.         print "Part 1: $flashes\n";
  54.     }
  55.  
  56.     if (keys %flashed == 100) {
  57.         print "Part 2: $t\n";
  58.         last;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement