-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.php
84 lines (70 loc) · 2.24 KB
/
day05.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
82
83
84
<?php
$filename = 'inputs/day5.txt';
$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$graph = [];
$ans = 0;
$ansPart2 = 0;
function isCorrectlyOrdered(array &$sequence): bool
{
global $graph;
$last = $sequence[0];
for ($i = 1; $i < count($sequence); $i++) {
if (!in_array($sequence[$i], ($graph[$last] ?? []))) {
return false;
}
$last = $sequence[$i];
}
return true;
}
function dfs(int $curr, array $path, array &$subgraph, int|null &$newMiddle, array &$sequence): bool
{
if (count($path) === count($sequence)) {
$newMiddle = $path[intdiv(count($path), 2)];
return true;
}
foreach (($subgraph[$curr] ?? []) as $nei) {
if (!in_array($nei, $path) and dfs($nei, array_merge($path, [$nei]), $subgraph, $newMiddle, $sequence)) {
return true;
}
}
return false;
}
function fixIncorrectlyOrdered(array $sequence): int
{
global $graph;
$subgraph = [];
for ($i = 0; $i < count($sequence) - 1; $i++) {
for ($j = $i + 1; $j < count($sequence); $j++) {
if (in_array($sequence[$j], $graph[$sequence[$i]] ?? [])) {
$subgraph[$sequence[$i]] = [...($subgraph[$sequence[$i]] ?? []), $sequence[$j]];
} elseif (in_array($sequence[$i], $graph[$sequence[$j]] ?? [])) {
$subgraph[$sequence[$j]] = [...($subgraph[$sequence[$j]] ?? []), $sequence[$i]];
}
}
}
$newMiddle = null;
foreach ($sequence as $start) {
if (isset($newMiddle)) {
break;
}
dfs($start, [$start], $subgraph, $newMiddle, $sequence);
}
assert(isset($newMiddle));
return $newMiddle;
}
foreach ($lines as $line) {
if (str_contains($line, '|')) {
list($src, $dest) = array_map('intval', explode('|', $line));
$graph[$src] = [...($graph[$src] ?? []), $dest];
} else {
$sequence = array_map('intval', explode(',', $line));
if (isCorrectlyOrdered($sequence)) {
assert(count($sequence) % 2 === 1);
$ans += $sequence[intdiv(count($sequence), 2)];
} else {
$ansPart2 += fixIncorrectlyOrdered($sequence);
}
}
}
echo $ans . "\n";
echo $ansPart2 . "\n";