Part 1
Problem: Starting at zero, move up one floor for every ‘(‘ and down one floor for every ‘)’.
Solution: Read in the input one character at a time using fgetc, then increment or decrement the current floor.
<?php
declare(strict_types=1);
error_reporting(E_ALL);
$floor = 0;
$fp = fopen('input', 'r');
while (($char = fgetc($fp)) !== false)
{
if ($char === '(')
{
$floor++;
}
elseif ($char === ')')
{
$floor--;
}
}
fclose($fp);
print("Final floor: $floor\n");
Part 2
Problem: Find the position of the first character which takes you into the basement.
Solution: As per the previous part, except keep a track of the current position and stop once the current floor is less than zero.
<?php
declare(strict_types=1);
error_reporting(E_ALL);
$floor = 0;
$position = 0;
$fp = fopen('input', 'r');
while (($char = fgetc($fp)) !== false)
{
$position++;
if ($char === '(')
{
$floor++;
}
elseif ($char === ')')
{
$floor--;
}
if ($floor < 0)
{
print("Position of basement: $position\n");
break;
}
}
fclose($fp);