63 lines
1.3 KiB
PHP
63 lines
1.3 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace AdventOfCode21;
|
||
|
|
||
|
class Day1 extends AbstractCommand
|
||
|
{
|
||
|
/**
|
||
|
* {@inheritdoc}
|
||
|
*/
|
||
|
protected static int $day = 1;
|
||
|
|
||
|
/**
|
||
|
* {@inheritdoc}
|
||
|
*/
|
||
|
protected function part1(array $data): int
|
||
|
{
|
||
|
$previous = null;
|
||
|
$increases = 0;
|
||
|
|
||
|
/** @var int $current */
|
||
|
foreach ($data as $current) {
|
||
|
if ($previous !== null && $previous < $current) {
|
||
|
++$increases;
|
||
|
}
|
||
|
|
||
|
$previous = $current;
|
||
|
}
|
||
|
|
||
|
return $increases;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* {@inheritdoc}
|
||
|
*/
|
||
|
protected function part2(array $data): int
|
||
|
{
|
||
|
$previousSum = null;
|
||
|
$increases = 0;
|
||
|
|
||
|
/**
|
||
|
* @var int $index
|
||
|
* @var int $indexValue
|
||
|
*/
|
||
|
foreach ($data as $index => $indexValue) {
|
||
|
// If no 'next' indexes are available, skip.
|
||
|
if (!isset($data[$index + 1], $data[$index + 2])) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
// Calculate the sum of the current value and the next two.
|
||
|
$newSum = $indexValue + (int) $data[$index + 1] + (int) $data[$index + 2];
|
||
|
|
||
|
if ($previousSum !== null && $previousSum < $newSum) {
|
||
|
++$increases;
|
||
|
}
|
||
|
|
||
|
$previousSum = $newSum;
|
||
|
}
|
||
|
|
||
|
return $increases;
|
||
|
}
|
||
|
}
|