patternphpMinor
PHP - Adventofcode - Day 1
Viewed 0 times
phpdayadventofcode
Problem
The code is correct and returns:
138
1771I'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:
The position that causes him to enter the basement
This can be significantly simplified e.g.:
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.
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 = 138The 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 = 1771Note 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 = 1771Context
StackExchange Code Review Q#113129, answer score: 4
Revisions (0)
No revisions yet.