musifter

AoC day 24, Perl

Dec 24th, 2020 (edited)
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.55 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(pairwise sum);
  7.  
  8. $| = 1;
  9. $; = ',';
  10.  
  11. my %Dirs = ('e'  => [ 0, 1], 'w'  => [ 0,-1],
  12.             'ne' => [ 1, 0], 'nw' => [ 1,-1],
  13.             'se' => [-1, 1], 'sw' => [-1, 0]);
  14.  
  15. my %flipped;
  16.  
  17. foreach my $walk (<>) {
  18.     my @hex = (0, 0);
  19.     foreach my $step ($walk =~ m#(e|w|ne|nw|se|sw)#g) {
  20.         @hex = pairwise { $a + $b } @hex, @{$Dirs{$step}};
  21.     }
  22.  
  23.     $flipped{$hex[0],$hex[1]} = !$flipped{$hex[0],$hex[1]};
  24. }
  25.  
  26. my @black_tiles = grep { $flipped{$_} } keys %flipped;
  27. print "Part 1: ", scalar( @black_tiles ), "\n";
  28.  
  29. # Part 2
  30. sub get_neighbours {
  31.     my @tile = split( /,/, shift );
  32.     return (map { join( ',', pairwise { $a + $b } @tile, @$_ ) } values %Dirs);
  33. }
  34.  
  35. # Initialize active tiles with counts of adjacent black tiles
  36. my %active;
  37. foreach my $tile (@black_tiles) {
  38.     $active{$tile} //= 0;
  39.     $active{$_}++ foreach (&get_neighbours( $tile ));
  40. }
  41. my $count = @black_tiles;
  42. foreach my $time (1 .. 100) {
  43.     my %next;
  44.  
  45.     foreach my $tile (keys %active) {
  46.         if ($flipped{$tile}) {
  47.             if (!$active{$tile} || $active{$tile} > 2) {
  48.                 $flipped{$tile} = 0;
  49.                 $count--;
  50.             }
  51.         } elsif ($active{$tile} == 2) {
  52.             $flipped{$tile} = 1;
  53.             $count++;
  54.         }
  55.  
  56.         if ($flipped{$tile}) {
  57.             $next{$tile} //= 0;
  58.             $next{$_}++ foreach (&get_neighbours( $tile ));
  59.         }
  60.     }
  61.  
  62.     print "[$time] $count  \r";
  63.     %active = %next;
  64. }
  65.  
  66. print "\n";
  67.  
Add Comment
Please, Sign In to add comment