You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
1.7 KiB
91 lines
1.7 KiB
2 weeks ago
|
<?php
|
||
|
|
||
|
final class Day2 extends Day {
|
||
|
|
||
|
function part1(): string {
|
||
|
$safeCount = 0;
|
||
|
|
||
|
foreach ($this->input as $line){
|
||
|
$levels = array_map('intval', explode(' ', $line));
|
||
|
|
||
|
$isSafe = true;
|
||
|
|
||
|
|
||
|
$direction = null;
|
||
|
for ($i = 0; $i < count($levels) - 1; $i++){
|
||
|
$levelNow = $levels[$i];
|
||
|
$levelThen = $levels[$i + 1];
|
||
|
|
||
|
$change = abs($levelThen - $levelNow);
|
||
|
if ($change < 1 || $change > 3){
|
||
|
$isSafe = false;
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
if ($direction === null){
|
||
|
$direction = $levelThen > $levelNow;
|
||
|
}
|
||
|
|
||
|
if ($direction !== ($levelThen > $levelNow)){
|
||
|
$isSafe = false;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if ($isSafe)
|
||
|
$safeCount++;
|
||
|
}
|
||
|
|
||
|
return strval($safeCount);
|
||
|
}
|
||
|
|
||
|
function part2(): string {
|
||
|
$safeCount = 0;
|
||
|
|
||
|
foreach ($this->input as $line){
|
||
|
$levels = array_map('intval', explode(' ', $line));
|
||
|
|
||
|
$isSafe = false;
|
||
|
|
||
|
for ($removeLevelIndex = -1; $removeLevelIndex < count($levels); $removeLevelIndex++){
|
||
|
$localLevels = $levels;
|
||
|
if ($removeLevelIndex > -1){
|
||
|
array_splice($localLevels, $removeLevelIndex, 1);
|
||
|
}
|
||
|
|
||
|
$levelSetIsSafe = true;
|
||
|
$direction = null;
|
||
|
for ($i = 0; $i < count($localLevels) - 1; $i++){
|
||
|
$levelNow = $localLevels[$i];
|
||
|
$levelThen = $localLevels[$i + 1];
|
||
|
|
||
|
$change = abs($levelThen - $levelNow);
|
||
|
if ($change < 1 || $change > 3){
|
||
|
$levelSetIsSafe = false;
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
if ($direction === null){
|
||
|
$direction = $levelThen > $levelNow;
|
||
|
}
|
||
|
|
||
|
if ($direction !== ($levelThen > $levelNow)){
|
||
|
$levelSetIsSafe = false;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
if ($levelSetIsSafe){
|
||
|
$isSafe = true;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if ($isSafe)
|
||
|
$safeCount++;
|
||
|
|
||
|
|
||
|
}
|
||
|
|
||
|
return strval($safeCount);
|
||
|
}
|
||
|
}
|