aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

sol2.pl (1544B) [raw]


      1 #!/usr/bin/env perl
      2 use strict;
      3 use warnings;
      4 
      5 open(my $fh, '<', 'input') or die "$!";
      6 # slurp
      7 my $content;
      8 {
      9     local $/;
     10     $content = <$fh>;
     11 }
     12 
     13 my @recs = split("\n\n", $content);
     14 my $n = 0;
     15 my %required = (
     16     byr => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 1920 && $_[0] <= 2002 },
     17     iyr  => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 2010 && $_[0] <= 2020 },
     18     eyr  => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 2020 && $_[0] <= 2030 },
     19     hgt  => sub {
     20         my $v = $_[0];
     21         if ($v =~ /^(\d\d+)(cm|in)$/) {
     22             if ($2 eq 'cm') { 
     23                 return ($1 >= 150 && $1 <= 193);
     24             } else {
     25                 return ($1 >= 59 && $1 <= 76);
     26             }
     27         } else {
     28             return 0;
     29         }
     30     },
     31     hcl  => sub { $_[0] =~ /^#[0-9a-f]{6}$/ },
     32     ecl  => sub { $_[0] =~ /^(amb|blu|brn|gry|grn|hzl|oth)$/ },
     33     pid => sub { $_[0] =~ /^\d{9}$/ },
     34 );
     35 REC:
     36 for my $r (@recs) {
     37 	my @fields = split(/\s+/, $r);
     38 
     39         # parse the fields, validate as you go
     40         my %has;
     41         for my $f (@fields) {
     42             my ($k, $v) = split(':', $f);
     43             $has{$k} = $v;
     44             if (!exists $required{$k}) {
     45                 next if $k eq 'cid'; #ok
     46 
     47                 print "unknown key: $k\n";
     48                 next REC;
     49             }
     50             if (!$required{$k}->($v)) {
     51                 # print "bad key/val: $k:$v\n";
     52                 next REC;
     53             }
     54         }
     55 
     56         # check they all exist
     57 	for my $req (keys %required) {
     58 		next REC if !exists $has{$req};
     59 	}
     60 	$n++;
     61 }
     62 print "$n\n";