tony311

advent day 4b solution

Dec 4th, 2020
427
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $input = file_get_contents("4.txt");
  2. $passports = explode("\n\n", $input);
  3. $valid = 0;
  4.  
  5. $sections = [
  6.     'byr' => function($data){ return strlen($data) == 4 && $data >= 1920 && $data <= 2002; },
  7.     'iyr' => function($data){ return strlen($data) == 4 && $data >= 2010 && $data <= 2020; },
  8.     'eyr' => function($data){ return strlen($data) == 4 && $data >= 2020 && $data <= 2030; },
  9.     'hgt' => function($data){ $unit = substr($data,strlen($data)-2,2); return ($unit == "in" && intval($data) >= 59 && intval($data) <= 76) || ($unit == "cm" && intval($data) >= 150 && intval($data) <= 193); },
  10.     'hcl' => function($data){ return preg_match("/^#[0-9a-f]{6}$/", $data); },
  11.     'ecl' => function($data){ return in_array($data, ['amb','blu','brn','gry','grn','hzl','oth']); },
  12.     'pid' => function($data){ return preg_match("/^[0-9]{9}$/", $data); },
  13. ];
  14.  
  15. foreach ($passports as $passport) {
  16.     // sneaky dirty PHP way of doing it - convert "byr:1980 hgt:160cm" to "byr=1980&hgt=160cm, then parse it into an array
  17.     $line = str_replace([" ", "\n",":"], ["&","&","="], $passport);
  18.     parse_str($line, $attrs);
  19.    
  20.     // normal way of doing it
  21.     //$line = str_replace("\n", " ", $passport);
  22.     //$attrs = explode(" ", $line);
  23.    
  24.     $valid++;
  25.     foreach ($sections as $section => $validatefunc) {
  26.         if ($attrs[$section] == null || !$validatefunc($attrs[$section])) {
  27.             $valid--;
  28.             break;
  29.         }
  30.     }
  31. }
  32.  
  33. echo $valid;
RAW Paste Data