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";