[2017-12-08] Solution for both puzzles

master
Elis Hirwing 2017-12-09 10:53:21 +01:00
parent 051e389130
commit 6cbbc8ea3d
Signed by: etu
GPG Key ID: D57EFA625C9A925F
2 changed files with 72 additions and 0 deletions

View File

@ -22,6 +22,8 @@ day7:
php day7/main.php
day8:
php day8/main.php
day9:
day10:
day11:

70
day8/main.php Normal file
View File

@ -0,0 +1,70 @@
<?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);
}