-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday6.py
93 lines (76 loc) · 2.43 KB
/
day6.py
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
from typing import List
def read_file(input) :
data = open(input,"r")
res = data.readlines()
res = list(map(lambda x: x[:-1].split(')'),res))
data.close()
return res
dictNodes = {}
class Node:
def __init__(self, name: str, parent) :
self.name = name
self.parent = parent
self.children = []
self.value = 0
dictNodes[name] = self
def addChildren(self, child) :
self.children.append(child)
def setParent(self, parentNode) :
self.parent = parentNode
noeudVide: Node = Node("vide", None)
def constructTree(L) :
for x in L :
parent, child = x
if parent in dictNodes :
parentNode = dictNodes[parent]
if child in dictNodes :
childNode = dictNodes[child]
childNode.setParent(parentNode)
else :
childNode = Node(child,parentNode)
parentNode.addChildren(childNode)
else :
parentNode = Node(parent, noeudVide)
if child in dictNodes :
childNode = dictNodes[child]
childNode.setParent(parentNode)
else :
childNode = Node(child, parentNode)
parentNode.addChildren(childNode)
return dictNodes["COM"]
def depthFirstSearch(node: Node) :
# print("on regarde le noeud", node.name)
if node.children == [] :
# print("il n'a pas d'enfants, sa value est ",node.value)
return
for x in node.children :
# print("ses enfants sont : ",list(map(lambda x:x.name,node.children)))
x.value = node.value+1
depthFirstSearch(x)
return
data = read_file("input-day6")
root = constructTree(data)
root.value = 0
depthFirstSearch(root)
total = 0
for x in dictNodes :
total+=dictNodes[x].value
#print(x,"enfants : ",dictNodes[x].children, "parent : ",dictNodes[x].parent)
print(total)
def path(a: Node, b: Node, root: Node) :
current = a
distanceToA = 1
parentsOfA = {'a': 0}
while root.name not in parentsOfA :
parentsOfA[current.parent.name] = distanceToA
current = current.parent
distanceToA +=1
current = b
distanceToB = 1
while 1 :
if current.parent.name in parentsOfA :
return parentsOfA[current.parent.name] + distanceToB - 2
else :
distanceToB+=1
current = current.parent
print(path(dictNodes["YOU"],dictNodes["SAN"],root))