[php] AOC day 16 part 1

Viewer

copydownloadembedprintName: AOC day 16 part 1
  1. #!/usr/local/bin/php
  2. <?php
  3.  
  4. class TicketTranslation {
  5.     public $fields;
  6.     public $my_ticket;
  7.     public $nearby_tickets;
  8.  
  9.     public function __construct() {
  10.         $file = file_get_contents(__DIR__.'/input.txt');
  11.         [$fields, $my_ticket, $nearby_tickets] = explode("\n\n", $file);
  12.  
  13.         $this->fields = [];
  14.         foreach (explode("\n", $fields) as $field) {
  15.             $matches = [];
  16.             // [name]: [n]-[n] or [n]-[n]
  17.             preg_match('/^([\w ]+): ([\d]+)-([\d]+) or ([\d]+)-([\d]+)/', $field, $matches);
  18.             $this->fields[] = [
  19.                 'name' => $matches[1],
  20.                 'ranges' => [
  21.                     [
  22.                         'from' => $matches[2],
  23.                         'to' => $matches[3],
  24.                     ],
  25.                     [
  26.                         'from' => $matches[4],
  27.                         'to' => $matches[5],
  28.                     ],
  29.                 ]
  30.             ];
  31.         }
  32.  
  33.         $my_ticket = explode("\n", $my_ticket)[1];
  34.         $this->my_ticket = explode(',', $my_ticket);
  35.  
  36.         $nearby_tickets = explode("\n", $nearby_tickets);
  37.         $nearby_tickets = array_splice($nearby_tickets, 1);
  38.         $this->nearby_tickets = [];
  39.         foreach ($nearby_tickets as $ticket) {
  40.             $this->nearby_tickets[] = explode(',', $ticket);
  41.         }
  42.     }
  43.  
  44.     public function part1() : int
  45.     {
  46.         $error_rate = 0;
  47.         foreach($this->nearby_tickets as $ticket) {
  48.             foreach ($ticket as $value) {
  49.                 $valid = false;
  50.                 foreach ($this->fields as $field) {
  51.                     if ($this->valid_field($value, $field)) {
  52.                         $valid = true;
  53.                     }
  54.                 }
  55.                 if (!$valid) {
  56.                     $error_rate += $value;
  57.                 }
  58.             }
  59.         }
  60.         return $error_rate;
  61.     }
  62.  
  63.     private function valid_field($value, $field) : bool
  64.     {
  65.         $result = false;
  66.         foreach ($field['ranges'] as $range) {
  67.             if ($range['from'] <= $value && $value <= $range['to']) {
  68.                 $result = true;
  69.             }
  70.         }
  71.         return $result;
  72.     }
  73. }
  74.  
  75. $tt = new TicketTranslation();
  76. $part1 = $tt->part1();
  77. echo("Part 1: $part1\n");

Editor

You can edit this paste and save as new:


File Description
  • AOC day 16 part 1
  • Paste Code
  • 17 Dec-2020
  • 2.27 Kb
You can Share it: