aoc2022

Advent of Code 2022 solutions in Perl.
git clone git://git.samirparikh.com/aoc2022
Log | Files | Refs | README

day03.pl (1200B) - raw


      1 #!/usr/local/bin/perl
      2 # day 2022-03
      3 
      4 use strict;
      5 use warnings;
      6 use v5.32;
      7 
      8 @ARGV = "input" unless @ARGV;
      9 chomp( my $input = do { local $/; <> } );
     10 
     11 my @rucksacks = split /\n/, $input;
     12 my $part1 = 0;
     13 my $part2 = 0;
     14 my $elf_count = 0;
     15 my $combined = '';
     16 
     17 foreach my $rucksack ( @rucksacks ) {
     18     my $compartment1 = substr( $rucksack, 0, ( length $rucksack ) / 2 );
     19     my $compartment2 = substr( $rucksack, ( length $rucksack ) / 2 ); 
     20     foreach my $item ( split //, $compartment1 ) {
     21         if ( $compartment2 =~ m/$item/ ) {
     22             if ( $item =~ m/[a-z]/ ) {
     23                 $part1 += ord( $item ) - ord( 'a' ) + 1;
     24             } else {
     25                 $part1 += ord( $item ) - ord( 'A' ) + 27;
     26             }
     27             last;
     28         }
     29     }
     30 
     31 # see https://abigail.github.io/HTML/AdventOfCode/2022/day-03.html
     32     $combined .= $rucksack . "\n";
     33     $elf_count++;
     34     if ( $elf_count % 3 == 0 ) {
     35         my ( $badge ) = $combined =~ m/(.).*\n.*\1.*\n.*\1/;
     36         $part2 += ( $badge =~ m/[a-z]/ ) ? ord( $badge ) - ord( 'a' ) + 1 :
     37                                            ord( $badge ) - ord( 'A' ) + 27;
     38         $combined = '';
     39     }
     40 }
     41 
     42 say "part 1: ", $part1;
     43 say "part 2: ", $part2;