Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(true);
- $/ = '';
- my %Rule;
- my %Patt;
- # Read Rules
- $_ = <>;
- foreach (split( "\n" )) {
- my ($num, $str) = m#(\d+): (.*)#;
- $Rule{$num} = $str;
- $Patt{$num} = $1 if ($str =~ m#([ab])#);
- }
- # Recursive function to fill out pattern table
- sub recurse_rules {
- my $num = shift;
- return ($Patt{$num}) if (exists $Patt{$num});
- my @tokens = split( " ", $Rule{$num} );
- my $ret = '(';
- foreach my $t (@tokens) {
- $ret .= ($t eq '|') ? '|' : &recurse_rules( $t );
- }
- $ret .= ')';
- $Patt{$num} = $ret;
- return ($ret);
- }
- # Build Pattern tables
- &recurse_rules( 0 );
- # Load signals to test
- my @sig = map { split( "\n" ) } <>;
- # Part 1:
- print "Part 1: ", (true { m#^@{[$Patt{0}]}$# } @sig), "\n";
- # Part 2: New verions of these rules (only used in 0: 8 11)
- # 8: 42 | 42 8
- # 11: 42 31 | 42 11 31
- my $patt8 = "$Patt{42}+";
- my $patt11 = "(?<ELEVEN>$Patt{42}$Patt{31}|$Patt{42}(?&ELEVEN)$Patt{31})";
- print "Part 2: ", (true { m#^$patt8$patt11$# } @sig), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement