-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-12.php
81 lines (63 loc) · 2.19 KB
/
day-12.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
$input = trim(file_get_contents(__DIR__ . '/input/day-12'));
$input = explode("\n", $input);
$start = microtime(true);
$moons = [];
$initial = [];
$id = 1;
foreach ($input as $item) {
preg_match('/(-?\d+).+?(-?\d+).+?(-?\d+)/', $item, $matches);
$moons[$id] = [
'id' => $id,
'pos' => [(int) $matches[1], (int) $matches[2], (int) $matches[3]],
'vel' => [0, 0, 0],
];
$initial[$id] = $moons[$id]['pos'];
$id++;
}
$intervals = [];
for ($i = 1; count($intervals) != 3; $i++) {
foreach (pairs($moons) as $pair) {
foreach (range(0, 2) as $axis) {
$diff = $pair[0]['pos'][$axis] <=> $pair[1]['pos'][$axis];
$moons[$pair[0]['id']]['vel'][$axis] -= $diff;
$moons[$pair[1]['id']]['vel'][$axis] += $diff;
}
}
foreach ($moons as $id => $moon) {
$moons[$id]['pos'][0] += $moons[$id]['vel'][0];
$moons[$id]['pos'][1] += $moons[$id]['vel'][1];
$moons[$id]['pos'][2] += $moons[$id]['vel'][2];
}
if ($i === 1000) {
$total = 0;
foreach ($moons as $id => $moon) {
$a = abs($moon['pos'][0]) + abs($moon['pos'][1]) + abs($moon['pos'][2]);
$b = abs($moon['vel'][0]) + abs($moon['vel'][1]) + abs($moon['vel'][2]);
$total += $a * $b;
}
echo 'Part 1: ' . $total . PHP_EOL;
}
for ($j = 0; $j < 3; $j++) {
if (isset($intervals[$j])) continue;
if ($moons[1]['pos'][$j] === $initial[1][$j] && $moons[1]['vel'][$j] === 0
&& $moons[2]['pos'][$j] === $initial[2][$j] && $moons[2]['vel'][$j] === 0
&& $moons[3]['pos'][$j] === $initial[3][$j] && $moons[3]['vel'][$j] === 0
&& $moons[4]['pos'][$j] === $initial[4][$j] && $moons[4]['vel'][$j] === 0
) {
$intervals[$j] = $i;
}
}
}
echo 'Part 2: ' . gmp_strval(gmp_lcm(gmp_lcm($intervals[0], $intervals[1]), $intervals[2])) . PHP_EOL;
function pairs($moons)
{
while (count($moons) > 1) {
$moon = array_splice($moons, 0, 1);
$moon = $moon[0];
foreach ($moons as $m) {
yield [$moon, $m];
}
}
}
echo 'Finished in ' . (microtime(true) - $start) . PHP_EOL;