[php] AOC day 16 part 1
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- #!/usr/local/bin/php
- <?php
- class TicketTranslation {
- public $fields;
- public $my_ticket;
- public $nearby_tickets;
- public function __construct() {
- $file = file_get_contents(__DIR__.'/input.txt');
- [$fields, $my_ticket, $nearby_tickets] = explode("\n\n", $file);
- $this->fields = [];
- foreach (explode("\n", $fields) as $field) {
- $matches = [];
- // [name]: [n]-[n] or [n]-[n]
- preg_match('/^([\w ]+): ([\d]+)-([\d]+) or ([\d]+)-([\d]+)/', $field, $matches);
- $this->fields[] = [
- 'name' => $matches[1],
- 'ranges' => [
- [
- 'from' => $matches[2],
- 'to' => $matches[3],
- ],
- [
- 'from' => $matches[4],
- 'to' => $matches[5],
- ],
- ]
- ];
- }
- $my_ticket = explode("\n", $my_ticket)[1];
- $this->my_ticket = explode(',', $my_ticket);
- $nearby_tickets = explode("\n", $nearby_tickets);
- $nearby_tickets = array_splice($nearby_tickets, 1);
- $this->nearby_tickets = [];
- foreach ($nearby_tickets as $ticket) {
- $this->nearby_tickets[] = explode(',', $ticket);
- }
- }
- public function part1() : int
- {
- $error_rate = 0;
- foreach($this->nearby_tickets as $ticket) {
- foreach ($ticket as $value) {
- $valid = false;
- foreach ($this->fields as $field) {
- if ($this->valid_field($value, $field)) {
- $valid = true;
- }
- }
- if (!$valid) {
- $error_rate += $value;
- }
- }
- }
- return $error_rate;
- }
- private function valid_field($value, $field) : bool
- {
- $result = false;
- foreach ($field['ranges'] as $range) {
- if ($range['from'] <= $value && $value <= $range['to']) {
- $result = true;
- }
- }
- return $result;
- }
- }
- $tt = new TicketTranslation();
- $part1 = $tt->part1();
- echo("Part 1: $part1\n");
Editor
You can edit this paste and save as new: