Skip to content

Instantly share code, notes, and snippets.

@maartenpaauw
Created December 12, 2023 08:04
Show Gist options
  • Save maartenpaauw/80ff15cb67f82331dd97cea40b64f820 to your computer and use it in GitHub Desktop.
Save maartenpaauw/80ff15cb67f82331dd97cea40b64f820 to your computer and use it in GitHub Desktop.
Advent of Code 2023 - Day 11
<?php
declare(strict_types=1);
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
$input = "...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....";
final readonly class Galaxies
{
public function __construct(
public int $x,
public int $y,
) {
}
public function distance(Galaxies $other, Collection $emptyColumns, Collection $emptyRows, int $multiplier): int
{
$emptyColumnCount = $emptyColumns
->filter(fn (int $row): bool => $row > min($this->x, $other->x) && $row < max($this->x, $other->x))
->count();
$emptyRowCount = $emptyRows
->filter(fn (int $row): bool => $row > min($this->y, $other->y) && $row < max($this->y, $other->y))
->count();
return abs($this->x - $other->x) + ($emptyColumnCount * $multiplier - $emptyColumnCount)
+ abs($this->y - $other->y) + ($emptyRowCount * $multiplier - $emptyRowCount);
}
}
$rows = Str::of($input)->explode(PHP_EOL);
$galaxies = $rows
->map(static function (string $line, int $y): array {
preg_match_all('/#/', $line, $matches, PREG_OFFSET_CAPTURE);
return Arr::map($matches[0], static fn (array $galaxies) => new Galaxies($galaxies[1], $y));
})
->flatten(1)
->sortBy(['y', 'x'])
->values();
$emptyColumns = Collection::range(0, strlen($rows->first()) - 1)
->diff(
$galaxies
->map(static fn (Galaxies $galaxies): int => $galaxies->x)
->unique()
->sort()
->values(),
)
->values();
$emptyRows = Collection::range(0, $rows->count() - 1)
->diff(
$galaxies
->map(static fn (Galaxies $galaxies): int => $galaxies->y)
->unique()
->sort()
->values(),
)
->values();
$combos = $galaxies->reduce(
static function (Collection $combos, Galaxies $left, int $index) use ($galaxies) {
$galaxies
->skip($index + 1)
->each(static fn (Galaxies $right) => $combos->add([$left, $right]));
return $combos;
},
new Collection(),
);
$part1 = $combos
->reduce(static function (int $sum, array $combo) use ($emptyColumns, $emptyRows): int {
[$left, $right] = $combo;
return $sum + $left->distance($right, $emptyColumns, $emptyRows, 2);
}, 0);
$part2 = $combos
->reduce(static function (int $sum, array $combo) use ($emptyColumns, $emptyRows): int {
[$left, $right] = $combo;
return $sum + $left->distance($right, $emptyColumns, $emptyRows, 1000000);
}, 0);
$result = [$part1, $part2];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment