summaryrefslogtreecommitdiff
path: root/2022/day07.py
blob: 7e3f593bb650897a8f21b741093163a94167c45f (plain)
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
#!/usr/bin/env python3

# import numpy as np
from functools import reduce
from re import findall
from copy import deepcopy
import sys

# filename = "in/day07.ref"
filename = "in/day07.pzl"
data = open(filename).read()
lines = [line for line in data.rstrip('\n').split('\n')]

res1 = 0
res2 = 0

pwd = '/'
fs = {'files':0}

for line in lines:

    l = line.split(' ')

    if l[0] == '$':
        if l[1] == 'cd':
            if l[2] == '/':
                pwd = '/'
            elif l[2] == '..':
                pwd = pwd[: -1 -pwd[:-1][::-1].find('/') ]
            else:
                pwd = pwd + l[2] + '/'

            # print(line)
            # print(pwd)

            p = pwd.strip('/').split('/')
            if p != ['']:
                fsp = fs
                for i in p:
                    if i not in fsp.keys():
                        fsp[i] = {'files':0}
                    fsp = fsp[i]

        elif l[1] == 'ls':
            continue

    else:
        if l[0] == 'dir':
            continue
        size, name = int(l[0]), l[1]

        p = pwd.strip('/').split('/')
        if p != ['']:
            fsp = fs
            for i in p:
                fsp = fsp[i]
            fsp['files'] += size
        else:
            fs['files'] += size


def print_fs(subfs, depth = 0):
    for d in subfs:
        if d == 'files':
            print(depth * ' ', d, ' ', subfs[d], sep = '')
        else:
            print(depth * ' ', d, sep = '')
            print_fs(subfs[d], depth+1)

def rec_fs(subfs):
    size = 0
    for d in subfs:
        if d == 'files':
            size += subfs[d]
            global sizes_one
            sizes_one.append(subfs[d])
            # print(d, size)
        else:
            size += rec_fs(subfs[d])

    global sizes_cumulative
    sizes_cumulative.append(size)

    return size

sizes_one = list()
sizes_cumulative = list()

# print(fs)
# print_fs(fs)

rec_fs(fs)

total_size = 70000000
needed_size = 30000000
used_size = sum(sizes_one)
delete_size = needed_size -(total_size - used_size)
total_size - used_size

res1 = sum(filter(lambda x: x <= 100000, sizes_cumulative))
res2 = list(filter(lambda x: x > delete_size, sorted(sizes_cumulative)))[0]

print('res1:', res1)
print('res2:', res2)