Advertisement
musifter

AoC 2023, day 19, part 1 (Perl)

Dec 19th, 2023
1,232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.02 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7. use List::Util      qw(sum);
  8.  
  9. # Paragraph mode, array of sections
  10. $/ = '';
  11. my @section = map {[split /\n/]} <>;
  12.  
  13. my %Rules;
  14.  
  15. foreach ($section[0]->@*) {
  16.     my ($flow, $str) = m#(\w+)\{(.*)\}#g;
  17.  
  18.     my @rules;
  19.     foreach my $rule (split( /,/, $str )) {
  20.         if ($rule =~ m#([xmas])([<>])(\d+):(\w+)#) {
  21.             push( @rules, "\$item{$1} $2 $3 and '$4'" );
  22.         } else {
  23.             push( @rules, "'$rule'" );
  24.         }
  25.     }
  26.  
  27.     $Rules{$flow} = \@rules;
  28. }
  29.  
  30. my $part1 = 0;
  31. foreach ($section[1]->@*) {
  32.     my %item = map { split /=/ } m#([xmas]=\d+)#g;
  33.     my $flow = 'in';
  34.  
  35.     FLOW:
  36.     while ($flow ne 'A' and $flow ne 'R') {
  37.         foreach my $rule ($Rules{$flow}->@*) {
  38.             my $result = eval( $rule ) // '';
  39.             if ($result) {
  40.                 $flow = $result;
  41.                 next FLOW;
  42.             }
  43.         }
  44.     }
  45.  
  46.     $part1 += sum values %item  if ($flow eq 'A');
  47. }
  48.  
  49. say "Part 1: $part1";
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement