2 changed files with 72 additions and 0 deletions
@ -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); |
||||
} |
Loading…
Reference in new issue