#!/usr/local/bin/php
<?php
class OperationOrder {
private $equations;
public function __construct() {
$in = file(__DIR__.'/input.txt');
$this->equations = array_map('trim', $in);
}
public function part1() : int
{
$result = 0;
foreach ($this->equations as $eq) {
$result += $this->evaluate($eq);
}
return $result;
}
public function evaluate($eq): int
{
return intval(preg_replace_callback_array(
[
'/^(.*)\(([\d *+]+)\)(.*)$/' => function($match) {
return $this->evaluate($match[1].$this->evaluate($match[2]).$match[3]);
},
'/^(.*) \+ ([\d]+)$/' => function ($match) {
return $this->evaluate($match[1]) + $match[2];
},
'/^(.*) \* ([\d]+)$/' => function ($match) {
return $this->evaluate($match[1]) * $match[2];
},
],
$eq
));
}
public function part2() : int
{
$result = 0;
foreach ($this->equations as $eq) {
$result += $this->evaluate2($eq);
}
return $result;
}
public function evaluate2($eq)
{
return preg_replace_callback_array(
[
'/^(.*)\(([\d *+]+)\)(.*)$/' => function($match) {
return $this->evaluate2($match[1].$this->evaluate2($match[2]).$match[3]);
},
'/^(.* )?([\d]+) \+ ([\d]+)(.*)$/' => function ($match) {
return $this->evaluate2($match[1].$match[2] + $match[3].$match[4]);
},
'/^([\d *]+) \* ([\d]+)$/' => function ($match) {
return $this->evaluate2($match[1]) * $match[2];
},
],
$eq
);
}
}
$oo = new OperationOrder();
$part1 = $oo->part1();
echo("Part 1: $part1\n");
$part2 = $oo->part2();
echo("Part 2: $part2\n");