From 25b46bc1158dcdf9c3cee8b64782ac05abe66c7a Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 20 Dec 2024 10:42:01 -0500 Subject: [PATCH] Complete day 2 part 1 --- 2024/day2/index.php | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/2024/day2/index.php b/2024/day2/index.php index 5103afe..0b1a7d7 100644 --- a/2024/day2/index.php +++ b/2024/day2/index.php @@ -8,5 +8,47 @@ function parse_reports(): array return array_map(fn (string $line) => explode(' ', $line), $lines); } +class Report { + public function __construct( + public bool $allIncreasing, + public bool $allDecreasing, + public bool $safeDifference, + ) {} + + public function isSafe(): bool + { + return $this->safeDifference && ($this->allIncreasing || $this->allDecreasing); + } +} + +function get_report_safety (array $report): Report { + $allIncreasing = true; + $allDecreasing = true; + $safeDifference = true; + + $safeDiff = function ($curr, $prev): bool { + $diff = abs((int)$curr - (int)$prev); + + return $diff > 0 && $diff <= 3; + }; + $increasing = fn ($curr, $prev): bool => (int)$curr > (int)$prev; + $decreasing = fn ($curr, $prev): bool => (int)$curr < (int)$prev; + + for ($i = 1;$i < count($report); $i++) + { + $curr = $report[$i]; + $prev = $report[$i - 1]; + + $allIncreasing = $allIncreasing && $increasing($curr, $prev); + $allDecreasing = $allDecreasing && $decreasing($curr, $prev); + $safeDifference = $safeDifference && $safeDiff($curr, $prev); + } + + return new Report($allIncreasing, $allDecreasing, $safeDifference); +} + $reports = parse_reports(); -print_r($reports); \ No newline at end of file +$reports = array_map('get_report_safety', $reports); +$safeReports = count(array_filter($reports, fn (Report $r) => $r->isSafe())); + +echo "Number of safe reports: $safeReports\n";