55 lines
1.4 KiB
PHP
55 lines
1.4 KiB
PHP
<?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);
|
|
}
|
|
|
|
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();
|
|
$reports = array_map('get_report_safety', $reports);
|
|
$safeReports = count(array_filter($reports, fn (Report $r) => $r->isSafe()));
|
|
|
|
echo "Number of safe reports: $safeReports\n";
|