advent_of_code_2020/day_18/part_2.php

58 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2020-12-18 09:56:50 +01:00
<?php
$operations = explode("\n", file_get_contents('input.txt'));
$results = [];
foreach ($operations as $i => $operation) {
$operation = evaluateParentheses($operation);
$operation = evaluateOperation($operation);
$results[] = (int) $operation;
echo sprintf('Line %u : %u%s', $i+1, $operation, "\n");
}
echo array_sum($results);
/**
* @param string $operation
*
* @return false|float|int
* @throws \Exception
*/
function evaluateOperation(string $operation)
{
while (!is_numeric($operation)) {
$original_operation = $operation;
$operation = preg_replace_callback(
'/(\d+) \+ (\d+)/',
static function ($matches) {
return (int)$matches[1] + (int)$matches[2];
},
$operation
);
if ($original_operation === $operation) {
$operation = preg_replace_callback(
'/(\d+) \* (\d+)/',
static function ($matches) {
return (int)$matches[1] * (int)$matches[2];
},
$operation
);
}
}
return $operation;
}
function evaluateParentheses($operation)
{
$result = preg_replace_callback('/\(([^\)\(]+)\)/', static function ($matches) {
return evaluateOperation($matches[1]);
}, $operation);
if ($result === $operation || $result === null) {
return $operation;
}
return evaluateParentheses($result);
}