-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.py
110 lines (82 loc) · 2.74 KB
/
day7.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
from enum import Enum
class Command(Enum):
command = "$"
cd = "cd"
list = "ls"
class Node:
def __init__(self, name, isDir, parent=None, size=None):
self.name = name
self.size = size
self.isDir = isDir
self.parent = parent
if self.isDir:
self.subElems = {}
def insert(self, elemName, size):
subElem = Node(elemName, True, self)
if size.isnumeric():
subElem = Node(elemName, False, self, int(size))
self.subElems[elemName] = subElem
def getHeadDir(currentDir):
if currentDir.parent is None:
return currentDir
return getHeadDir(currentDir.parent)
def positionItself(currentDir, param):
match param:
case "..":
return currentDir.parent
case "/":
return getHeadDir(currentDir)
case _:
return currentDir.subElems[param]
def constructHierarchy(home, lines):
currentDir = home
currentCommand = Command
for i in range(0, len(lines)):
if lines[i].startswith("$"):
fields = lines[i].split()
# take the executed command
match fields[1]:
case "cd":
currentDir = positionItself(currentDir, fields[2])
case "ls":
currentCommand = Command.list
else:
# for now it means currentCommand = Command.list
data = lines[i].split()
currentDir.insert(data[1], data[0])
def calculateSizes(current):
sum = 0
for name, item in current.subElems.items():
if item.isDir:
calculateSizes(item)
sum += item.size
current.size = sum
def getAllUnderLimit(currentDir, limit):
sum = 0
if currentDir.size <= limit:
sum += currentDir.size
for name, item in currentDir.subElems.items():
if item.isDir:
sum += getAllUnderLimit(item, limit)
return sum
def findMinimalBiggerThan(currentDir, needToFree, currentMin):
if currentMin > currentDir.size >= needToFree:
currentMin = currentDir.size
for name, item in currentDir.subElems.items():
if item.isDir:
min = findMinimalBiggerThan(item, needToFree, currentMin)
if min < currentMin:
currentMin = min
return currentMin
def findOneToDelete(home, total, needed):
unused = total - home.size
needToFree = needed - unused
return findMinimalBiggerThan(home, needToFree, home.size)
if __name__ == '__main__':
f = open('day7_input.txt', 'r')
lines = f.readlines()
home = Node("/", True)
constructHierarchy(home, lines)
calculateSizes(home)
print(getAllUnderLimit(home, 100000))
print(findOneToDelete(home, 70000000, 30000000))