aoc2022

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

day02.pl (1627B) - raw


      1 #!/usr/local/bin/perl
      2 # day 2022-02
      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 %defeats = (
     12     rock        => 'scissors',
     13     scissors    => 'paper',
     14     paper       => 'rock',
     15     );
     16 
     17 my %translate = (
     18     A           => 'rock',
     19     B           => 'paper',
     20     C           => 'scissors',
     21     X           => 'rock',
     22     Y           => 'paper',
     23     Z           => 'scissors',
     24     );
     25 
     26 my %translate2 = (
     27     X           => 'lost',
     28     Y           => 'draw',
     29     Z           => 'won',
     30     );
     31 
     32 my %score = (
     33     rock        => 1,
     34     paper       => 2,
     35     scissors    => 3,
     36     lost        => 0,
     37     draw        => 3,
     38     won         => 6,
     39     );
     40 
     41 my @rounds = split /\n/, $input;
     42 my $part1_score = 0;
     43 my $part2_score = 0;
     44 
     45 foreach my $round ( @rounds ) {
     46     my ( $opponent, $me ) = split /\s/, $round;
     47     $part1_score += $score{ $translate{ $me } };
     48     if ( $translate{ $me } eq $translate{ $opponent } ) {
     49         $part1_score += $score{ draw };
     50     } elsif ( $defeats{ $translate{ $me } } eq $translate{ $opponent } ) {
     51         $part1_score += $score{ won };
     52     }
     53 
     54     $part2_score += $score{ $translate2{ $me } };
     55     if ( $me eq 'X' ) { # must lose
     56         $part2_score += $score{ $defeats{ $translate{ $opponent } } };
     57     } elsif ( $me eq 'Y' ) { # draw
     58         $part2_score += $score{ $translate{ $opponent } };
     59     } else { # win
     60         my @matching_keys = grep { $defeats{ $_ } eq $translate{ $opponent} } keys %defeats;
     61         $part2_score += $score{ $matching_keys[0] };
     62     }
     63 }
     64 
     65 say "part 1: ", $part1_score;
     66 say "part 2: ", $part2_score;