advent-of-code/2024/day2/index.php

55 lines
1.4 KiB
PHP
Raw Normal View History

2024-12-06 09:34:23 -05:00
<?php declare(strict_types=1);
function parse_reports(): array
{
$raw = file_get_contents('./input.txt');
$lines = explode("\n", trim($raw));
return array_map(fn (string $line) => explode(' ', $line), $lines);
}
2024-12-20 10:42:01 -05:00
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);
}
2024-12-06 09:34:23 -05:00
$reports = parse_reports();
2024-12-20 10:42:01 -05:00
$reports = array_map('get_report_safety', $reports);
$safeReports = count(array_filter($reports, fn (Report $r) => $r->isSafe()));
echo "Number of safe reports: $safeReports\n";