Advertisement
musifter

AoC 2023 day 16 (Perl)

Dec 17th, 2023
917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.78 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7. use List::Util      qw(max any);
  8.  
  9. use Math::Vector::Real;
  10. my ($Y,$X) = Math::Vector::Real->canonical_base(2);
  11. my @Dir = ($Y, $X, -$Y, -$X);                      # SENW (0123)
  12.  
  13. my %Piece = (
  14.                 '|'  => [  [0], [0,2],   [2], [0,2]],
  15.                 '-'  => [[1,3],   [1], [1,3],   [3]],
  16.  
  17.                 '\\' => [[1], [0], [3], [2]],
  18.                 '/'  => [[3], [2], [1], [0]],
  19.  
  20.                 '.'  => [[0], [1], [2], [3]],
  21.                 '~'  => [[], [], [], []],
  22.             );
  23.  
  24.  
  25. # Read in grid, adding sentinel ~s to right and bottom
  26. my @Grid = map { chomp; [split(//), '~'] } <>;
  27. push( @Grid, [('~') x $Grid[0]->@*] );
  28.  
  29. sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
  30. sub print_grid  { say "\t", join( '', @$_ ) foreach (@Grid);      }
  31.  
  32. sub energize {
  33.     my ($start, $start_dir) = @_;
  34.  
  35.     my %visit;
  36.     my @queue = ([$start, $start_dir]);
  37.     my $count = 0;
  38.  
  39.     BEAM:
  40.     while (my $state = shift @queue) {
  41.         my ($pos, $dir) = @$state;
  42.  
  43.         next BEAM  if (exists $visit{$pos} and any {$_ == $dir} $visit{$pos}->@*);
  44.         next BEAM  if (grid_at($pos) eq '~');
  45.  
  46.         $count++   if (!exists $visit{$pos});
  47.         push( $visit{$pos}->@*, $dir );
  48.  
  49.         foreach my $move ($Piece{grid_at($pos)}[$dir]->@*) {
  50.             push( @queue, [$pos + $Dir[$move], $move] );
  51.         }
  52.     }
  53.  
  54.     return ($count);
  55. }
  56.  
  57. my @col;
  58. foreach my $i (0 .. $#Grid) {
  59.     print ::stderr  "Pos: $i\r";
  60.     push( @col, &energize( V(0,$i), 0 ) );
  61.     push( @col, &energize( V($#Grid - 1, $i), 2 ) );
  62.     push( @col, &energize( V($i,0), 1 ) );
  63.     push( @col, &energize( V($i, $#Grid - 1), 3 ) );
  64. }
  65.  
  66. say "\nPart 1: ", $col[2];
  67. say "Part 2: ", max( @col );
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement