-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-8.php
63 lines (44 loc) · 1.22 KB
/
day-8.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
<?php
$input = trim(file_get_contents('input/' . substr(basename(__FILE__), 0, -4)));
$input = $input2 = explode(' ', $input);
$nodes = [];
echo 'Answer 1: ' . tree($input) . PHP_EOL;
function tree(&$input) {
$children = $input[0];
$metadata = $input[1];
$sum = 0;
$input = array_slice($input, 2);
for ($i = 0; $i < $children; $i++) {
$sum += tree($input);
}
for ($i = 0; $i < $metadata; $i++) {
$sum += $input[$i];
}
$input = array_slice($input, $metadata);
return $sum;
}
echo 'Answer 2: ' . tree2($input2) . PHP_EOL;
function tree2(&$input) {
$children = $input[0];
$metadata = $input[1];
$input = array_slice($input, 2);
$sum = 0;
if ($children == 0) {
for ($i = 0; $i < $metadata; $i++) {
$sum += $input[$i];
}
$input = array_slice($input, $metadata);
return $sum;
}
$childValues = [];
for ($i = 0; $i < $children; $i++) {
$childValues[$i + 1] = tree2($input);
}
for ($i = 0; $i < $metadata; $i++) {
if (isset($childValues[$input[$i]])) {
$sum += $childValues[$input[$i]];
}
}
$input = array_slice($input, $metadata);
return $sum;
}