-
Notifications
You must be signed in to change notification settings - Fork 0
/
bags.php
executable file
·61 lines (49 loc) · 1.4 KB
/
bags.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
#!/usr/bin/php
<?php
const STARTING_BAG = 'shiny gold';
$bags = [];
while(($line = fgets(STDIN)) !== FALSE) {
$line = trim($line, " \t\n\r.");
$line = str_replace([' bags', ' bag'], ['', ''], $line);
$line = explode(" contain ", $line);
$container = $line[0];
if(!isset($bags[$container])) {
$bags[$container] = [
'children' => [],
'parents' => [],
];
}
if($line[1] === 'no other') continue;
foreach(explode(", ", $line[1]) as $item) {
[$number, $type] = explode(" ", $item, 2);
$bags[$container]['children'][] = [
'number' => $number,
'type' => $type,
];
if(!isset($bags[$type])) {
$bags[$type] = [
'children' => [],
'parents' => [],
];
}
$bags[$type]['parents'][] = $container;
}
}
function find_outer_bags(&$bags, $current_bag) {
$solutions = [];
foreach($bags[$current_bag]['parents'] as $parent) {
$solutions = array_merge($solutions, [$parent], find_outer_bags($bags, $parent));
}
return $solutions;
}
$solution = array_values(array_unique(find_outer_bags($bags, STARTING_BAG)));
print_r($solution);
echo "possible outer bags: " . count($solution) . "\n";
function count_inner_bags(&$bags, $current_bag) {
$inner_bags = 0;
foreach($bags[$current_bag]['children'] as $child) {
$inner_bags += $child['number'] * (1 + count_inner_bags($bags, $child['type']));
}
return $inner_bags;
}
echo "inner bags: " . count_inner_bags($bags, STARTING_BAG) . "\n";