Skip to content

Instantly share code, notes, and snippets.

@maartenpaauw
Created December 9, 2023 13:58
Show Gist options
  • Save maartenpaauw/581d7b5624d33ae7d987b2f8f7b20082 to your computer and use it in GitHub Desktop.
Save maartenpaauw/581d7b5624d33ae7d987b2f8f7b20082 to your computer and use it in GitHub Desktop.
Advent of Code 2023 - Day 9
<?php
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$input = "0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45";
$histories = Str::of($input)
->explode(PHP_EOL)
->mapInto(Stringable::class)
->map(static function (Stringable $report) {
return $report
->explode(' ')
->map(static fn (string $measurement): int => intval($measurement));
})
->mapInto(History::class);
final readonly class History
{
public function __construct(
private Collection $sequence,
) {
}
public function predictFirst(): int
{
return $this->process(new Collection([$this->sequence->reverse()]));
}
public function predictLast(): int
{
return $this->process(new Collection([$this->sequence]));
}
/**
* @param Collection<array-key, Collection<array-key, int>> $groups
*/
private function process(Collection $groups): int
{
if ($groups->last()->every(static fn (int $difference): bool => $difference === 0)) {
return $groups
->reduce(static fn (int $prediction, Collection $sequence): int => $sequence->last() + $prediction, 0);
}
return $this->process(
$groups->push(
$groups
->last()
->eachCons(2)
->map(static fn (Collection $window): int => $window->last() - $window->first()),
),
);
}
}
$part1 = $histories->map(static fn (History $history): int => $history->predictLast())->sum();
$part2 = $histories->map(static fn (History $history): int => $history->predictFirst())->sum();
$result = [$part1, $part2];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment