HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP - Adventofcode - Day 1

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpdayadventofcode

Problem



The code is correct and returns:

138
1771


I'm looking for the most elegant way / the best time complexity to tackle the problem ;)

Solution

To what floor do the instructions take Santa?

There is no need to go character by character to determine that, instead:

$puzzle = '...';

$up = substr_count($puzzle, '(');
$down = substr_count($puzzle, ')');
$floor = $up - $down;
// $floor = 138


The position that causes him to enter the basement

This can be significantly simplified e.g.:

$puzzle = '...';

$position = 0;
$floor = 0;
while ($floor !== -1) {
    $char = $puzzle[$position];
    ($char === '(') ? $floor++ : $floor--;
    $position++;
}
// $position = 1771


Note that there's no need to continue to the end once the answer has been obtained - this alone make determining the answer faster.

This doesn't defend against out-of-bound problems, but it also doesn't need to.

Code Snippets

$puzzle = '...';

$up = substr_count($puzzle, '(');
$down = substr_count($puzzle, ')');
$floor = $up - $down;
// $floor = 138
$puzzle = '...';

$position = 0;
$floor = 0;
while ($floor !== -1) {
    $char = $puzzle[$position];
    ($char === '(') ? $floor++ : $floor--;
    $position++;
}
// $position = 1771

Context

StackExchange Code Review Q#113129, answer score: 4

Revisions (0)

No revisions yet.