Benjamin Kraft 2 weeks ago
parent 68bdad57a7
commit c1ff5f7242
  1. 91
      public/days/Day2.php

@ -0,0 +1,91 @@
<?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);
}
}
Loading…
Cancel
Save