adventofcode/src/Y21/Day6.php

90 lines
1.9 KiB
PHP
Raw Normal View History

2021-12-07 09:49:43 +01:00
<?php
namespace trizz\AdventOfCode\Y21;
2021-12-07 09:49:43 +01:00
use JetBrains\PhpStorm\Immutable;
2021-12-09 22:25:59 +00:00
use trizz\AdventOfCode\Solution;
2021-12-07 09:49:43 +01:00
2022-11-29 19:52:02 +01:00
final class Day6 extends Solution
2021-12-07 09:49:43 +01:00
{
public static null|int|string $part1ExampleResult = 5934;
2022-11-29 19:52:02 +01:00
public static null|int|string $part1Result = 350917;
public static null|int|string $part2ExampleResult = 26_984_457_539;
2022-11-29 19:52:02 +01:00
public static null|int|string $part2Result = 1_592_918_715_629;
2021-12-07 09:49:43 +01:00
/**
* @var int[]
2022-11-29 19:52:02 +01:00
*
2021-12-07 09:49:43 +01:00
* @psalm-param array{int: int}
*/
2022-11-29 19:52:02 +01:00
#[Immutable] private array $startState = [
2021-12-07 09:49:43 +01:00
8 => 0,
7 => 0,
6 => 0,
5 => 0,
4 => 0,
3 => 0,
2 => 0,
1 => 0,
0 => 0,
];
#[\Override]
public function part1(array $data): int
2021-12-07 09:49:43 +01:00
{
return $this->processPuzzle(80, $data[0]);
}
#[\Override]
public function part2(array $data): int
2021-12-07 09:49:43 +01:00
{
return $this->processPuzzle(256, $data[0]);
}
/**
* @param int[] $state
*
2022-11-29 19:52:02 +01:00
* @psalm-param array{int: int} $state
2021-12-07 09:49:43 +01:00
*/
2022-11-29 19:52:02 +01:00
private function processDay(array $state): array
2021-12-07 09:49:43 +01:00
{
$newState = $state;
/**
* @var int $key
* @var int $stateValue
*/
foreach ($state as $key => $stateValue) {
$newKey = $key - 1;
if ($newKey < 0) {
$newState[8] = $stateValue;
$newKey = 6;
}
$newState[$key] -= $stateValue;
$newState[$newKey] += $stateValue;
}
return $newState;
}
2022-11-29 19:52:02 +01:00
private function processPuzzle(int $numberOfDays, string $data): int
2021-12-07 09:49:43 +01:00
{
$state = $this->startState;
2022-11-29 19:52:02 +01:00
array_map(static function (string $stateValue) use (&$state): void {
2021-12-07 09:49:43 +01:00
++$state[(int) $stateValue];
}, explode(',', $data));
for ($day = 0; $day < $numberOfDays; ++$day) {
$state = $this->processDay($state);
}
return (int) array_sum($state);
}
}