🚧 Commence le jour 12

This commit is contained in:
Clément 2020-12-15 10:17:37 +01:00
parent da17833029
commit 3698c4b997

71
day_12/part_1.php Normal file
View File

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