Complete day 2 part 1
This commit is contained in:
parent
372bdf7147
commit
25b46bc115
@ -8,5 +8,47 @@ function parse_reports(): array
|
|||||||
return array_map(fn (string $line) => explode(' ', $line), $lines);
|
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 = parse_reports();
|
||||||
print_r($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";
|
||||||
|
Loading…
Reference in New Issue
Block a user