Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use List::Util qw(sum);
- # Paragraph mode, array of sections
- $/ = '';
- my @section = map {[split /\n/]} <>;
- my %Rules;
- foreach ($section[0]->@*) {
- my ($flow, $str) = m#(\w+)\{(.*)\}#g;
- my @rules;
- foreach my $rule (split( /,/, $str )) {
- if ($rule =~ m#([xmas])([<>])(\d+):(\w+)#) {
- push( @rules, "\$item{$1} $2 $3 and '$4'" );
- } else {
- push( @rules, "'$rule'" );
- }
- }
- $Rules{$flow} = \@rules;
- }
- my $part1 = 0;
- foreach ($section[1]->@*) {
- my %item = map { split /=/ } m#([xmas]=\d+)#g;
- my $flow = 'in';
- FLOW:
- while ($flow ne 'A' and $flow ne 'R') {
- foreach my $rule ($Rules{$flow}->@*) {
- my $result = eval( $rule ) // '';
- if ($result) {
- $flow = $result;
- next FLOW;
- }
- }
- }
- $part1 += sum values %item if ($flow eq 'A');
- }
- say "Part 1: $part1";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement