Guest User

Untitled

a guest
Dec 8th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.09 KB | None | 0 0
  1. <?php
  2. class Node
  3. {
  4.     private $data = array();
  5.     private $offset = 0;
  6.     private $meta_count = 0;
  7.     private $child_count = 0;
  8.     private $meta = array();
  9.     private $children = /* Node */array();
  10.  
  11.     public function __construct($data, $offset)
  12.     {
  13.         $this->data = $data;
  14.         $this->offset = $offset;
  15.     }
  16.  
  17.     protected function get_length():int
  18.     {
  19.         $length = 2; //Identifiers
  20.         $length += $this->meta_count;
  21.  
  22.         foreach ($this->children as $child)
  23.         {
  24.             $length += $child->get_length();
  25.         }
  26.  
  27.         return $length;
  28.     }
  29.  
  30.     public function parse_data()
  31.     {
  32.         $this->child_count = $this->data[$this->offset];
  33.         $this->meta_count = $this->data[$this->offset+1];
  34.  
  35.         $offset = $this->offset+2;
  36.  
  37.         for($i=0;$i<$this->child_count;$i++)
  38.         {
  39.             $node = new Node($this->data, $offset);
  40.             $this->children[] = $node;
  41.             $node->parse_data();
  42.             $offset += $node->get_length();
  43.         }
  44.  
  45.         $this->meta = array_slice($this->data, $offset, $this->meta_count);
  46.  
  47.     }
  48.  
  49.     public function get_meta_sum():int //Part 1
  50.     {
  51.         $sum = array_sum($this->meta);
  52.  
  53.         foreach ($this->children as $child)
  54.         {
  55.             $sum += $child->get_meta_sum();
  56.         }
  57.  
  58.         return $sum;
  59.     }
  60.  
  61.     public function get_meta_sum_indexed():int //Part 2
  62.     {
  63.         $sum = 0;
  64.  
  65.         if($this->child_count>0)
  66.         {
  67.             foreach ($this->meta as $m)
  68.             {
  69.                 if($m < 1) continue;
  70.  
  71.                 if(isset($this->children[$m-1]))
  72.                 {
  73.                     $sum += $this->children[$m-1]->get_meta_sum_indexed();
  74.                 }
  75.             }
  76.         } else {
  77.             $sum = array_sum($this->meta);
  78.         }
  79.  
  80.         return $sum;
  81.     }
  82.  
  83. }
  84.  
  85. $input = file_get_contents('input.txt');
  86.  
  87. $data = explode(' ', $input);
  88.  
  89. $node = new Node($data, 0);
  90. $node->parse_data();
  91.  
  92. echo 'Part 1: '. $node->get_meta_sum() . PHP_EOL;
  93. echo 'Part 2: '. $node->get_meta_sum_indexed() . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment