71 lines
1.8 KiB
PHP
71 lines
1.8 KiB
PHP
<?php
|
|
|
|
$instructions = explode("\n", file_get_contents('input.txt'));
|
|
|
|
const NORTH = 'N';
|
|
const SOUTH = 'S';
|
|
const EAST = 'E';
|
|
const WEST = 'W';
|
|
const LEFT = 'L';
|
|
const RIGHT = 'R';
|
|
const FORWARD = 'F';
|
|
|
|
$facings = [NORTH, EAST, SOUTH, WEST];
|
|
|
|
$facing = EAST;
|
|
$east = 0;
|
|
$north = 0;
|
|
|
|
function doingInstruction($direction, $value)
|
|
{
|
|
global $north, $east, $facings, $facing;
|
|
switch ($direction) {
|
|
case NORTH:
|
|
$north += $value;
|
|
break;
|
|
case SOUTH:
|
|
$north -= $value;
|
|
break;
|
|
case EAST:
|
|
$east += $value;
|
|
break;
|
|
case WEST:
|
|
$east -= $value;
|
|
break;
|
|
case LEFT:
|
|
$turns = $value / 90;
|
|
$array_position = array_search($facing, $facings);
|
|
$array_max = 4;
|
|
for ($i = $turns; $i > 0; $i--) {
|
|
$array_position--;
|
|
if ($array_position === -1) {
|
|
$array_position = $array_max - 1;
|
|
}
|
|
}
|
|
$facing = $facings[$array_position];
|
|
break;
|
|
case RIGHT:
|
|
$turns = $value / 90;
|
|
$array_position = array_search($facing, $facings);
|
|
$array_max = 4;
|
|
for ($i = 0; $i < $turns; $i++) {
|
|
$array_position++;
|
|
if ($array_position === $array_max) {
|
|
$array_position = 0;
|
|
}
|
|
}
|
|
$facing = $facings[$array_position];
|
|
break;
|
|
case FORWARD:
|
|
doingInstruction($facing, (int)$value);
|
|
break;
|
|
}
|
|
}
|
|
|
|
foreach ($instructions as $instruction) {
|
|
$direction = $instruction[0];
|
|
$value = (int)substr($instruction, 1);
|
|
doingInstruction($direction, $value);
|
|
}
|
|
|
|
echo abs($east) + abs($north); |