From c1ff5f7242c0fd8b4baac50bb8926041e5c52da0 Mon Sep 17 00:00:00 2001 From: Benjamin Kraft Date: Thu, 2 Jan 2025 21:15:44 +0100 Subject: [PATCH] day 2 --- public/days/Day2.php | 91 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 public/days/Day2.php diff --git a/public/days/Day2.php b/public/days/Day2.php new file mode 100644 index 0000000..9edea55 --- /dev/null +++ b/public/days/Day2.php @@ -0,0 +1,91 @@ +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); + } +} \ No newline at end of file