Untitled

mail@pastecode.io avatar
unknown
perl6
7 months ago
1.6 kB
10
Indexable
Never
grammar Game {
    rule TOP { <prefix> <round>+ }
    rule prefix { Game <num>\: }
    rule round { [<cubes>[\, ]?]+[\; ]? }

    proto rule cubes          {*}
          rule cubes:sym<red> { <num> 'red' }
          rule cubes:sym<green> { <num> 'green' }
          rule cubes:sym<blue> { <num> 'blue' }

    token num { \d+ }
}

class PossibleGame {
    method TOP ($/) { make [&&] $<round>.map(*.made); }
    method round ($/) { make [&&] $<cubes>.map(*.made); }

    method cubes:sym<red> ($/) { make $<num> <= 12; }
    method cubes:sym<green> ($/) { make $<num> <= 13; }
    method cubes:sym<blue> ($/) { make $<num> <= 14; }
}

class MinimumCubesPower {
    method TOP ($/) { make [*] $<round>.map(*.made).reduce(&merge-max).values; }
    method round ($/) { make $<cubes>.map(*.made).reduce(&merge-max); }

    method cubes:sym<red> ($/) { make {red => +$<num>, green => 0, blue => 0}; }
    method cubes:sym<green> ($/) { make {red => 0, green => +$<num>, blue => 0}; }
    method cubes:sym<blue> ($/) { make {red => 0, green => 0, blue => +$<num>}; }
}

sub merge-max(%a, %b) {
    my %result;
    for <red green blue> -> $k {
        %result{$k} = max(%a{$k}, %b{$k});
    }

    return %result;
}

sub part1(@input) {
    return @input
        .map({Game.parse($_, actions => PossibleGame)})
        .grep(*.made)
        .map({$_<prefix><num>})
        .sum
}

sub part2(@input) {
    return @input
        .map({Game.parse($_, actions => MinimumCubesPower).made})
        .sum
}

my @input = "input.txt".IO.lines;
my $p1 = part1 @input;
my $p2 = part2 @input;

put "Part 1: $p1"; # 2285
put "Part 2: $p2"; # 77021
Leave a Comment