63 lines
1.5 KiB
Perl
63 lines
1.5 KiB
Perl
#!/usr/bin/env perl
|
|
use warnings;
|
|
use strict;
|
|
|
|
my $filename = '../data/input.txt';
|
|
|
|
open(FH, '<', $filename) or die $!;
|
|
|
|
sub possible_id {
|
|
my $line = $_[0];
|
|
my $reds = $_[1];
|
|
my $greens = $_[2];
|
|
my $blues = $_[3];
|
|
my @colors = qw(red green blue);
|
|
my @quantities = ($reds, $greens, $blues);
|
|
# Extract the id and game draws
|
|
my @game_parts = split /:/, $line, 2;
|
|
my @id_parts = split / /, $game_parts[0], 2;
|
|
my $id = $id_parts[1];
|
|
my @game_plays = split /;/, $game_parts[1];
|
|
foreach my $play (@game_plays) {
|
|
my @color_counts = (0, 0, 0);
|
|
my @play_draws = split /,/, $play;
|
|
foreach my $draw (@play_draws) {
|
|
my @draw_parts = split / /, $draw;
|
|
my $color = $draw_parts[2];
|
|
my $amount = int($draw_parts[1]);
|
|
for ((0..2)) {
|
|
my $idx = $_;
|
|
my $limit_color = $colors[$idx];
|
|
my $limit_amount = $quantities[$idx];
|
|
if ($color eq $limit_color) {
|
|
$color_counts[$idx] += $amount;
|
|
}
|
|
}
|
|
}
|
|
# print join(", ", @color_counts) . "\n";
|
|
for ((0..2)) {
|
|
if ($quantities[$_] < $color_counts[$_]) {
|
|
return 0;
|
|
|
|
}
|
|
}
|
|
}
|
|
return int($id);
|
|
}
|
|
|
|
my $reds_limit = 12;
|
|
my $greens_limit = 13;
|
|
my $blues_limit = 14;
|
|
|
|
my $sum = 0;
|
|
while (<FH>) {
|
|
# print $_;
|
|
my $id = possible_id($_, $reds_limit, $greens_limit, $blues_limit);
|
|
$sum += $id;
|
|
# print $id . "\n";
|
|
}
|
|
|
|
close(FH);
|
|
|
|
print $sum . "\n";
|