-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-6.php
59 lines (43 loc) · 1.15 KB
/
day-6.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
<?php
$input = trim(file_get_contents(__DIR__ . '/input/day-6'));
$input = explode("\n", $input);
$start = microtime(true);
$orbits = [];
$orbitedBy = [];
foreach ($input as $data) {
$a = explode(')', $data);
$orbits[$a[1]] = $a[0];
$orbitedBy[$a[0]][] = $a[1];
}
$count = 0;
foreach ($orbits as $moon => $planet) {
$count++;
while (isset($orbits[$planet])) {
$count++;
$planet = $orbits[$planet];
}
}
echo 'Part 1: ' . $count . PHP_EOL;
$queue = [[$orbits['YOU'], 0]];
$passed = ['YOU'];
do {
[$planet, $steps] = array_shift($queue);
$next = [];
if (isset($orbits[$planet]) && !in_array($orbits[$planet], $passed)) {
$next[] = $orbits[$planet];
}
foreach ($orbitedBy[$planet] ?? [] as $item) {
if (!in_array($item, $passed)) {
$next[] = $item;
}
}
foreach ($next as $item) {
if ($item === $orbits['SAN']) {
echo 'Part 2: ' . ($steps + 1) . PHP_EOL;
break 2;
}
array_push($queue, [$item, $steps + 1]);
}
$passed[] = $planet;
} while(true);
echo 'Finished in ' . (microtime(true) - $start) . PHP_EOL;