Advertisement
musifter

AoC 2023, day 3 (Perl)

Dec 3rd, 2023 (edited)
1,118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.10 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::Util      qw(sum product);
  7.  
  8. # Read in grid, adding sentinel .s around all four sides (because substr)
  9. my @grid = map { chomp; ".$_." } <>;
  10.  
  11. push   ( @grid, '.' x length $grid[0] );
  12. unshift( @grid, '.' x length $grid[0] );
  13.  
  14. my $part1 = 0;
  15. my %gears;              # hash from location of gear to list of part numbers
  16.  
  17. foreach my $line (1 .. $#grid - 1) {
  18.     while ($grid[$line] =~ m#(\d+)#g) {
  19.         my $num = $1;
  20.         my $x = pos($grid[$line]) - length($num) - 1;   # left edge of search block
  21.  
  22.         # Search surrounding block for parts and gears
  23.         my $found = 0;
  24.         foreach my $y ($line - 1 .. $line + 1) {
  25.             my $str = substr( $grid[$y], $x, length($num) + 2 );
  26.  
  27.             $found = 1                                    if ($str =~ m#[^.0-9]#);
  28.             push( $gears{$y, $x + pos($str)}->@*, $num )  while ($str =~ m#\*#g);
  29.         }
  30.  
  31.         $part1 += $num if ($found);
  32.     }
  33. }
  34.  
  35. my $part2 = sum map { product @$_ } grep { @$_ == 2 } values %gears;
  36.  
  37. print "Part 1: $part1\n";
  38. print "Part 2: $part2\n";
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement