This repository has been archived by the owner on Jul 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day12.php
100 lines (81 loc) · 1.95 KB
/
Day12.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
<?php
class Node {
private $id;
/** @var Node[] */
private $contacts = [];
private static $seenInCount = [];
/**
* Node constructor.
*
* @param $id
*/
public function __construct($id)
{
$this->id = $id;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
public function addContact(Node $contact)
{
if (!in_array($contact, $this->contacts)) {
$this->contacts[] = $contact;
}
}
public function countContacts($depth = 0)
{
$sum = 0;
if (!in_array($this, self::$seenInCount)) {
self::$seenInCount[] = $this;
$sum++;
foreach ($this->contacts as $contact) {
$sum += $contact->countContacts($depth + 1);
}
}
if ($depth == 0) {
self::$seenInCount = [];
}
return $sum;
}
/**
* @return Node[]
*/
public function getGroup() {
$this->countContacts(1);
$group = self::$seenInCount;
self::$seenInCount = [];
return $group;
}
}
$input = file_get_contents('input12');
$connections = explode("\n", trim($input));
/** @var Node[] $nodes */
$nodes = [];
foreach ($connections as $connection) {
$node = new Node(substr($connection, 0, strpos($connection, ' <->')));
$nodes[$node->getId()] = $node;
}
foreach ($connections as $connection) {
list($nodeId, $contacts) = explode(' <-> ', $connection);
$node = $nodes[(int)$nodeId];
foreach (explode(', ', $contacts) as $contactId) {
$contact = $nodes[$contactId];
$node->addContact($contact);
}
}
$node = $nodes[0];
echo $node->countContacts() . "\n";
$groups = [];
foreach ($nodes as $node) {
foreach ($groups as $group) {
if (in_array($node, $group)) {
continue 2;
}
}
$groups[] = $node->getGroup();
}
echo count($groups) . "\n";