Advent of Code 2022 - 7

Day 7: No Space Left On Device

https://adventofcode.com/2022/day/7

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
path = {}
size = {}
total_size = {}

def sizeof(p):
s = size[p]
if len(path[p]) > 0:
for sub in path[p]:
s += sizeof(sub)
return s


def preprocess():
curr = []
with open('07.txt', 'r') as fp:
for line in fp:
line = line.strip().split()
if line[1] == 'cd':
if line[2] == '..':
curr.pop()
else:
curr.append(line[2])
path[''.join(curr)] = []
size[''.join(curr)] = 0
elif line[1] == 'ls':
continue
elif line[0] == 'dir':
path[''.join(curr)].append(''.join(curr)+line[1])
else:
size[''.join(curr)] += int(line[0])
for p in path:
total_size[p] = sizeof(p)


preprocess()

Part One

1
print(sum([s for s in total_size.values() if s <= 100000]))

Answer: 1325919

Part Two

1
2
3
4
5
6
7
8
used = sum(list(size.values()))
disc = 70000000
unused = 30000000
delete = disc
for s in total_size.values():
if (used - s + unused) <= (disc) and s < delete:
delete = s
print(delete)

Answer: 2050735