82 lines
1.7 KiB
Perl
82 lines
1.7 KiB
Perl
#!/usr/bin/env perl
|
|
|
|
use strict;
|
|
use warnings;
|
|
use feature qw/ say /;
|
|
use Test::More;
|
|
|
|
my $input = "input";
|
|
my %shape = ( "X" => 1, "Y" => 2, "Z" => 3 );
|
|
my %win = ( "X" => "C", "Y" => "A", "Z" => "B" );
|
|
my %draw = ( "X" => "A", "Y" => "B", "Z" => "C" );
|
|
my %lose = ( "X" => "B", "Y" => "C", "Z" => "A" );
|
|
my %result = ( "X" => 0, "Y" => 3, "Z" => 6 );
|
|
my %win_r = reverse %win;
|
|
my %draw_r = reverse %draw;
|
|
my %lose_r = reverse %lose;
|
|
|
|
ok( score( "A", "Y" ) == 8 );
|
|
ok( score( "B", "X" ) == 1 );
|
|
ok( score( "C", "Z" ) == 6 );
|
|
ok( score_part2( "A", "Y" ) == 4 );
|
|
ok( score_part2( "B", "X" ) == 1 );
|
|
ok( score_part2( "C", "Z" ) == 7 );
|
|
done_testing();
|
|
|
|
say "Part 1";
|
|
|
|
sub score {
|
|
my ( $p1, $p2 ) = @_;
|
|
my $score = $shape{$p2};
|
|
if ( $win{$p2} eq $p1 ) {
|
|
$score += 6;
|
|
}
|
|
elsif ( $draw{$p2} eq $p1 ) {
|
|
$score += 3;
|
|
}
|
|
return $score;
|
|
}
|
|
|
|
open( my $fh, "<", $input )
|
|
or die "Can't open < $input: $!";
|
|
|
|
my $total_score = 0;
|
|
while ( my $line = <$fh> ) {
|
|
chomp $line;
|
|
my ( $p1, $p2 ) = split( / /, $line );
|
|
$total_score += score( $p1, $p2 );
|
|
}
|
|
close($fh);
|
|
|
|
say $total_score;
|
|
|
|
say "Part 2";
|
|
|
|
sub score_part2 {
|
|
my ( $p1, $r ) = @_;
|
|
my $score = $result{$r};
|
|
if ( $score == 6 ) {
|
|
$score += $shape{ $win_r{$p1} };
|
|
}
|
|
elsif ( $score == 3 ) {
|
|
$score += $shape{ $draw_r{$p1} };
|
|
}
|
|
else {
|
|
$score += $shape{ $lose_r{$p1} };
|
|
}
|
|
return $score;
|
|
}
|
|
|
|
open( my $fh2, "<", $input )
|
|
or die "Can't open < $input: $!";
|
|
|
|
my $total_score_2 = 0;
|
|
while ( my $line = <$fh2> ) {
|
|
chomp $line;
|
|
my ( $p1, $r ) = split( / /, $line );
|
|
$total_score_2 += score_part2( $p1, $r );
|
|
}
|
|
close($fh2);
|
|
|
|
say $total_score_2;
|