You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.3 KiB
PHP

<?php
// https://adventofcode.com/2017/day/8
function puzzle(string $input, bool $returnTopValue = false) : int {
$lines = explode(PHP_EOL, $input);
$variables = [];
$topValue = 0;
$shouldRun = function (string $comparison, int $subject, int $compareTo) : bool {
if ($comparison === '>') {
return $subject > $compareTo;
} elseif ($comparison === '<') {
return $subject < $compareTo;
} elseif ($comparison === '==') {
return $subject === $compareTo;
} elseif ($comparison === '>=') {
return $subject >= $compareTo;
} elseif ($comparison === '<=') {
return $subject <= $compareTo;
} elseif ($comparison === '!=') {
return $subject !== $compareTo;
}
echo "Missing comparison code: ".$comparison.PHP_EOL;
exit;
};
$runCommandFunction = function (string $type, int $argument, int $base) : int {
if ($type === 'inc') {
return $base + $argument;
} elseif ($type === 'dec') {
return $base - $argument;
}
echo "Missing command: ".$type.PHP_EOL;
exit;
};
foreach ($lines as $line) {
$parts = explode(' ', $line);
// Extract parts
$subject = $parts[0];
$command = $parts[1];
$commandArgument = $parts[2];
$ifSubject = $parts[4];
$ifComparison = $parts[5];
$ifCompareTo = $parts[6];
// Default values to zero if they aren't set
$variables[$subject] = $variables[$subject] ?? 0;
$variables[$ifSubject] = $variables[$ifSubject] ?? 0;
if ($shouldRun($ifComparison, $variables[$ifSubject], $ifCompareTo)) {
$variables[$subject] = $runCommandFunction($command, $commandArgument, $variables[$subject]);
if ($variables[$subject] > $topValue) {
$topValue = $variables[$subject];
}
}
}
if ($returnTopValue) {
return $topValue;
}
rsort($variables);
return array_shift($variables);
}
echo 'First challange solution:'.PHP_EOL;
echo puzzle(trim(file_get_contents(dirname(__FILE__).'/input.txt'))).PHP_EOL.PHP_EOL;
echo 'Second challange solution:'.PHP_EOL;
echo puzzle(trim(file_get_contents(dirname(__FILE__).'/input.txt')), true).PHP_EOL.PHP_EOL;