59 lines
1.1 KiB
PHP
59 lines
1.1 KiB
PHP
|
<?php
|
||
|
$input_file = '../inputs/day2.txt';
|
||
|
if (file_exists($input_file)) {
|
||
|
$input = file_get_contents($input_file);
|
||
|
if ($input != null) {
|
||
|
$instructions = explode("\n", $input);
|
||
|
print 'Part 1 answer: ' . solve_part_one($instructions) . "\n";
|
||
|
print 'Part 2 answer: ' . solve_part_two($instructions) . "\n";
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function solve_part_one(array $instructions): int
|
||
|
{
|
||
|
$pos = 0;
|
||
|
$depth = 0;
|
||
|
|
||
|
foreach ($instructions as $inst) {
|
||
|
[$instruction, $param] = explode(" ", $inst);
|
||
|
$param = (int)$param;
|
||
|
if ($instruction == 'forward') {
|
||
|
$pos += $param;
|
||
|
}
|
||
|
|
||
|
if ($instruction == 'up') {
|
||
|
$depth -= $param;
|
||
|
}
|
||
|
|
||
|
if ($instruction == 'down') {
|
||
|
$depth += $param;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return $pos * $depth;
|
||
|
}
|
||
|
|
||
|
function solve_part_two(array $instructions): int
|
||
|
{
|
||
|
$pos = 0;
|
||
|
$depth = 0;
|
||
|
$aim = 0;
|
||
|
|
||
|
foreach ($instructions as $inst) {
|
||
|
[$instruction, $param] = explode(" ", $inst);
|
||
|
$param = (int)$param;
|
||
|
if ($instruction == 'forward') {
|
||
|
$pos += $param;
|
||
|
$depth += $aim * $param;
|
||
|
}
|
||
|
|
||
|
if ($instruction == 'up') {
|
||
|
$aim -= $param;
|
||
|
}
|
||
|
|
||
|
if ($instruction == 'down') {
|
||
|
$aim += $param;
|
||
|
}
|
||
|
}
|
||
|
return $pos * $depth;
|
||
|
}
|