-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.php
117 lines (88 loc) · 2.39 KB
/
code.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
require_once __DIR__ . '/../../lib/php/utils.php';
$input = readInput(__DIR__);
// Task code
function part01(array $input): int
{
$bagGraph = transpose(
createBagGraph($input)
);
return traverse($bagGraph, 'shiny gold') - 1;
}
function part02(array $input): int
{
$graph = createBagGraph($input);
return countBags($graph, 'shiny gold')-1;
}
function createBagGraph(array $input): array
{
$bagGraph = [];
foreach ($input as $line) {
$matches = null;
$matched = preg_match('/(.*) bags contain (.*)/', $line, $matches);
if (!$matched) {
continue;
}
[, $outerBag, $innerBags] = $matches;
$bagGraph[$outerBag] = [];
$innerBagList = explode(', ', $innerBags);
foreach ($innerBagList as $innerBag) {
$matches = null;
$matched = preg_match('/(\d+) (.*) (bags?)/', $innerBag, $matches);
if (!$matched) {
continue;
}
[, $weight, $bag] = $matches;
$bagGraph[$outerBag][$bag] = $weight;
}
}
return $bagGraph;
}
function transpose(array $graph): array
{
$result = [];
foreach ($graph as $outerBag => $innerBags) {
foreach ($innerBags as $innerBag => $weight) {
if (!array_key_exists($innerBag, $result)) {
$result[$innerBag] = [];
}
$result[$innerBag][] = $outerBag;
}
}
return $result;
}
function traverse(array $graph, string $node, array &$hits = []): int
{
if (in_array($node, $hits, true)) {
return 0;
}
$hits[] = $node;
$count = 1;
foreach ($graph[$node] ?? [] as $parent) {
$count += traverse($graph, $parent, $hits);
}
return $count;
}
function countBags(array $graph, string $node): int
{
$innerBags = $graph[$node];
$count = 1;
foreach ($innerBags as $innerBag => $weight) {
$count += countBags($graph, $innerBag) * $weight;
}
return $count;
}
// Execute
calcExecutionTime();
$result01 = part01($input);
$result02 = part02($input);
$executionTime = calcExecutionTime();
writeln('Solution Part 1: ' . $result01);
writeln('Solution Part 2: ' . $result02);
writeln('Execution time: ' . $executionTime);
saveBenchmarkTime($executionTime, __DIR__);
// Task test
testResults(
[326, 5635], // Expected
[$result01, $result02], // Result
);