Advertisement
musifter

AoC 2024, day 19 (Perl)

Dec 18th, 2024 (edited)
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.79 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say state);
  7. use List::Util      qw(sum);
  8.  
  9. $| = 1;
  10.  
  11. # Read sections:
  12. $/ = '';
  13. my @section = map {[split /\n/]} <>;
  14. my @patt = split( /, /, $section[0][0] );
  15.  
  16. # Part 1
  17. my $patt_re = '^(' . join('|', @patt) . ')*$';
  18. my @good = grep { m#$patt_re# } $section[1]->@*;
  19. say "Part 1: ", scalar @good;
  20.  
  21. # Part 2
  22. sub recurse_count {
  23.     my ($str) = @_;
  24.     state %memo;
  25.  
  26.     return ($memo{$str})      if (exists $memo{$str});
  27.     return ($memo{$str} = 1)  if ($str eq '');
  28.  
  29.     my $ret = 0;
  30.     foreach my $patt (@patt) {
  31.         my $new_str = $str;
  32.         $ret += &recurse_count( $new_str ) if ($new_str =~ s#^$patt##);
  33.     }
  34.  
  35.     return ($memo{$str} = $ret);
  36. }
  37.  
  38. say "Part 2: ", sum map {&recurse_count( $_ )} @good;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement