|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | +dirs = {} |
| 5 | +current_dir = "/" |
| 6 | + |
| 7 | +def eval_command(command: str, output: list[str]): |
| 8 | + global dirs, current_dir |
| 9 | + if command.startswith('cd'): |
| 10 | + path = command.split(' ')[1] |
| 11 | + current_dir = os.path.abspath(os.path.join(current_dir, path)) |
| 12 | + if dirs.get(current_dir) == None: |
| 13 | + dirs[current_dir] = {} |
| 14 | + if command == 'ls': |
| 15 | + for line in output: |
| 16 | + if re.compile('\d+').match(line): |
| 17 | + size = int(line.split(' ')[0]) |
| 18 | + filename = line.split(' ')[1] |
| 19 | + dirs[current_dir][filename] = size |
| 20 | + |
| 21 | + |
| 22 | + pass |
| 23 | + |
| 24 | +def calculate_dir_sizes(lines): |
| 25 | + i = 0 |
| 26 | + while len(lines) > i: |
| 27 | + line = lines[i] |
| 28 | + if line.startswith('$'): |
| 29 | + command = line.split('$ ')[1].replace("\n", ""); |
| 30 | + i += 1 |
| 31 | + output = [] |
| 32 | + while len(lines) > i: |
| 33 | + if lines[i].startswith('$'): break |
| 34 | + output.append(lines[i].replace('\n', '')) |
| 35 | + i += 1 |
| 36 | + eval_command(command, output) |
| 37 | + |
| 38 | + dir_sizes = {} |
| 39 | + |
| 40 | + for path in dirs: |
| 41 | + subpaths = [] |
| 42 | + filesize = 0 |
| 43 | + for pathb in dirs: |
| 44 | + if pathb.startswith(path): |
| 45 | + subpaths.append(pathb) |
| 46 | + for subpath in subpaths: |
| 47 | + files = dirs[subpath] |
| 48 | + for file in files: |
| 49 | + filesize += int(files[file]) |
| 50 | + dir_sizes[path] = filesize |
| 51 | + return dir_sizes |
| 52 | + |
| 53 | +def part1(lines: list[str]): |
| 54 | + dir_sizes = calculate_dir_sizes(lines) |
| 55 | + |
| 56 | + small_dirs = {} |
| 57 | + |
| 58 | + for filepath in dir_sizes: |
| 59 | + if dir_sizes[filepath] < 100000: |
| 60 | + small_dirs[filepath] = dir_sizes[filepath] |
| 61 | + |
| 62 | + size_sum = 0 |
| 63 | + for filepath in small_dirs: |
| 64 | + size_sum += small_dirs[filepath] |
| 65 | + return size_sum |
| 66 | + |
| 67 | + |
| 68 | +def part2(lines): |
| 69 | + dir_sizes = calculate_dir_sizes(lines) |
| 70 | + min_size = 30000000 |
| 71 | + used = 70000000 - dir_sizes['/'] |
| 72 | + needed = min_size - used |
| 73 | + smallest = dir_sizes['/'] |
| 74 | + |
| 75 | + for filepath in dir_sizes: |
| 76 | + size = dir_sizes[filepath] |
| 77 | + if size < smallest and size > needed: |
| 78 | + smallest = dir_sizes[filepath] |
| 79 | + |
| 80 | + return smallest |
| 81 | + |
| 82 | + |
| 83 | +dirname = os.path.dirname(__file__) |
| 84 | +filename = os.path.join(dirname, '../input.txt') |
| 85 | +with open(filename) as f: |
| 86 | + lines = f.readlines() |
| 87 | + |
| 88 | +print(part1(lines)) |
| 89 | +print(part2(lines)) |
0 commit comments