-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd07_2.php
67 lines (51 loc) · 2.36 KB
/
d07_2.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
<?php
$lines = file('input_d07.txt', FILE_IGNORE_NEW_LINES);
$processes = [];
$unbalanced = false;
foreach ($lines as $line) {
$parts = explode('->', trim($line));
$sub_parts = explode(' ', trim($parts[0]));
$processes[$sub_parts[0]]['weight'] = substr($sub_parts[1], 1, -1);
if (count($parts) > 1) {
// Has children
$processes[$sub_parts[0]]['children'] = explode(', ', trim($parts[1]));
}
}
function sum_weight(&$processes, &$unbalanced, $process_name) {
$weight = $processes[$process_name]['weight'];
if (isset($processes[$process_name]['children'])) {
$child_weights = [];
foreach ($processes[$process_name]['children'] as $child) {
$processes[$child]['sum_weight'] = sum_weight($processes, $unbalanced, $child);
$weight += $processes[$child]['sum_weight'];
array_push($child_weights, $processes[$child]['sum_weight']);
}
// All children should have same weights
if (count(array_unique($child_weights)) > 1 && $unbalanced === false) {
$unbalanced = true;
if (count($child_weights) === 2) {
// One of the childrens need change. Does not matter which one
// However the problem assumes there will only one process has
// the wrong weight and need to be changed, so this is not happening.
} else {
// These calculation might be way more complicated than it should be
foreach (array_count_values($child_weights) as $weight => $count) {
if ($count === 1) {
$weight_index = array_search($weight, $child_weights);
break;
}
}
$other_weight = ($weight_index === 0) ? $child_weights[1] : $child_weights[0];
$child_name = $processes[$process_name]['children'][$weight_index];
echo 'Process weight should be: '
. ($processes[$child_name]['weight'] - ($processes[$child_name]['sum_weight'] - $other_weight))
. PHP_EOL;
}
// var_dump($child_weights);
// var_dump($processes[$process_name]['children']);
// var_dump($process_name);
}
}
return $weight;
}
sum_weight($processes, $unbalanced, 'hlqnsbe'); // root process