Advertisement
musifter

AoC 2024 day 12, part 1 (Perl)

Dec 12th, 2024 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.15 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7.  
  8. use Math::Vector::Real;
  9.  
  10. my ($vy,$vx) = Math::Vector::Real->canonical_base(2);
  11. my @Dirs = ($vy, $vx, -$vy, -$vx);
  12.  
  13. # Read in grid, adding sentinel ~s to right and bottom
  14. my @Grid = map { chomp; [split(//), '~'] } <>;
  15. push( @Grid, [('~') x $Grid[0]->@*] );
  16.  
  17. sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
  18. sub print_grid  { say "\t", join( '', @$_ ) foreach (@Grid); }
  19.  
  20. my $part1 = 0;
  21. my %visited;
  22.  
  23. foreach my $y (0 .. $#Grid - 1) {
  24.     foreach my $x (0 .. $Grid[0]->$#* - 1) {
  25.         my $start = V($y,$x);
  26.         next if ($visited{$start});
  27.  
  28.         my $plant = grid_at($start);
  29.         my $area  = 0;
  30.         my $inner = 0;
  31.         my @field = ($start);
  32.  
  33.         while (my $pos = shift @field) {
  34.             next if ($visited{$pos});
  35.             my @neigh = grep { grid_at($_) eq $plant } map { $pos + $_ } @Dirs;
  36.  
  37.             $inner += scalar @neigh;
  38.             $area++;
  39.             $visited{$pos}++;
  40.  
  41.             push( @field, @neigh );
  42.         }
  43.  
  44.         $part1 += $area * (4 * $area - $inner);
  45.     }
  46. }
  47.  
  48. say "Part 1: $part1";
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement