Advertisement
musifter

AoC 2022, day 3 (Perl)

Dec 3rd, 2022
1,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.71 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. # Table where letters are in priority positions
  7. my $table = join( '', @{['^', 'a' .. 'z', 'A' .. 'Z']} );
  8.  
  9. my $part1 = 0;
  10. my $part2 = 0;
  11. my $badge = '';
  12.  
  13. while (<>) {
  14.     chomp;
  15.  
  16.     # Part 1
  17.     # Insert sentinel in middle, sum if match on both sides.
  18.     substr( $_, length() / 2, 0, '#' );
  19.     $part1 += index( $table, $1 ) if (m/(\w).*#.*\1/);
  20.  
  21.     # Part 2
  22.     # Append lines with sentinel between them.
  23.     $badge .= "$_#";
  24.  
  25.     # When a match occurs across three, sum and empty badge.
  26.     if ($badge =~ m/(\w).*#.*\1.*#.*\1/) {
  27.         $part2 += index( $table, $1 );
  28.         $badge = '';
  29.     }
  30. }
  31.  
  32. print "Part 1: $part1\n";
  33. print "Part 2: $part2\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement