-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path08.php
65 lines (55 loc) · 1.48 KB
/
08.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
$time_start = microtime(true);
$input = trim(file_get_contents('08.txt'));
$grid = explode("\n", $input);
class Antenna {
public function __construct(
public int $row,
public int $col,
) {}
}
function count_unique_antinodes(array $frequency_antennas, int $width, int $height, bool $pt2 = false)
{
$antinodes = [];
foreach ($frequency_antennas as $frequency => $antennas) {
foreach ($antennas as $a) {
foreach ($antennas as $b) {
if ($a === $b) continue;
$rd = ($b->row - $a->row);
$cd = ($b->col - $a->col);
$r = $pt2 ? $a->row : $b->row;
$c = $pt2 ? $a->col : $b->col;
do {
$r += $rd;
$c += $cd;
if ($r < 0 || $c < 0 || $r >= $height || $c >= $width) {
break;
}
$antinodes["$r-$c"] = true;
} while ($pt2);
}
}
}
return count($antinodes);
}
$height = count($grid);
$width = strlen($grid[0]);
$antennas = [];
for ($r = 0; $r < $height; $r++) {
for ($c = 0; $c < $width; $c++) {
if ($grid[$r][$c] === '.') continue;
if (!isset($antennas[$grid[$r][$c]])) {
$antennas[$grid[$r][$c]] = [];
}
$antennas[$grid[$r][$c]][] = new Antenna($r, $c);
}
}
$pt1 = count_unique_antinodes($antennas, $width, $height);
$pt2 = count_unique_antinodes($antennas, $width, $height, true);
echo "--- Day 8: Resonant Collinearity ---", PHP_EOL;
echo "Part 1: ", $pt1, PHP_EOL;
echo "Part 2: ", $pt2, PHP_EOL;
echo "Took ", (microtime(true) - $time_start) * 1000, " ms", PHP_EOL;
echo PHP_EOL;
assert($pt1 === 252);
assert($pt2 === 839);