Browse Source

[2017-12-08] Solution for both puzzles

master
Elis Hirwing 4 years ago
parent
commit
6cbbc8ea3d
Signed by: etu GPG Key ID: D57EFA625C9A925F
  1. 2
      Makefile
  2. 70
      day8/main.php

2
Makefile

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

70
day8/main.php

@ -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…
Cancel
Save