2015 Day 1

Posted on Dec 1, 2015

Part 1

Problem

Take a list of characters from a file and find the final ‘floor’ that Santa ends up on, based on the characters.

General solution

Read in each character and increment or decrement the current floor.

Solution: PHP

Open the file and read in each line, changing the floor based on the character.

<?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

As before, but find the location of the character which causes Santa to enter the basement, i.e. floor = -1.

Solution: PHP

Same as part 1, except stop when the 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);