Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Node
- {
- private $data = array();
- private $offset = 0;
- private $meta_count = 0;
- private $child_count = 0;
- private $meta = array();
- private $children = /* Node */array();
- public function __construct($data, $offset)
- {
- $this->data = $data;
- $this->offset = $offset;
- }
- protected function get_length():int
- {
- $length = 2; //Identifiers
- $length += $this->meta_count;
- foreach ($this->children as $child)
- {
- $length += $child->get_length();
- }
- return $length;
- }
- public function parse_data()
- {
- $this->child_count = $this->data[$this->offset];
- $this->meta_count = $this->data[$this->offset+1];
- $offset = $this->offset+2;
- for($i=0;$i<$this->child_count;$i++)
- {
- $node = new Node($this->data, $offset);
- $this->children[] = $node;
- $node->parse_data();
- $offset += $node->get_length();
- }
- $this->meta = array_slice($this->data, $offset, $this->meta_count);
- }
- public function get_meta_sum():int //Part 1
- {
- $sum = array_sum($this->meta);
- foreach ($this->children as $child)
- {
- $sum += $child->get_meta_sum();
- }
- return $sum;
- }
- public function get_meta_sum_indexed():int //Part 2
- {
- $sum = 0;
- if($this->child_count>0)
- {
- foreach ($this->meta as $m)
- {
- if($m < 1) continue;
- if(isset($this->children[$m-1]))
- {
- $sum += $this->children[$m-1]->get_meta_sum_indexed();
- }
- }
- } else {
- $sum = array_sum($this->meta);
- }
- return $sum;
- }
- }
- $input = file_get_contents('input.txt');
- $data = explode(' ', $input);
- $node = new Node($data, 0);
- $node->parse_data();
- echo 'Part 1: '. $node->get_meta_sum() . PHP_EOL;
- echo 'Part 2: '. $node->get_meta_sum_indexed() . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment