-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9.py
97 lines (84 loc) · 2.05 KB
/
9.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
# pylint: skip-file
# mypy: ignore-errors
# flake8: noqa
files_raw = open("9.txt", "r").read()
def get_files(files_raw):
files = []
is_file = True
id = 0
for digit in files_raw:
if is_file:
files.append((int(digit), id, 0))
id += 1
else:
files.append((int(digit), []))
is_file = not is_file
return files
def get_checksum(files):
i = 0
total = 0
for file in files:
if type(file[1]) == list:
for sub_file in file[1]:
(count, id) = sub_file
for _ in range(count):
total += id * i
i += 1
i += file[0]
else:
(count, id, used) = file
for _ in range(count):
total += id * i
i += 1
i += used
return total
# Part 1:
files = get_files(files_raw)
next_free = 1
i = len(files) - 1
while i > -1 and next_free < len(files):
if i <= next_free:
break
if type(files[i][1]) == list:
i -= 1
continue
(left, id, used) = files[i]
(size, space) = files[next_free]
to_move = min(size, left)
size -= to_move
left -= to_move
used += to_move
space.append((to_move, id))
files[i] = (left, files[i][1], used)
files[next_free] = (size, space)
if left == 0:
i -= 1
if size == 0:
next_free += 2
print(get_checksum(files))
# Part 2:
files = get_files(files_raw)
i = len(files) - 1
while i > -1:
if type(files[i][1]) == list:
i -= 1
continue
(left, id, used) = files[i]
next_free = None
for j in range(1, i, 2):
if files[j][0] >= left:
next_free = j
break
if next_free is None:
i -= 1
continue
(size, space) = files[next_free]
to_move = min(size, left)
size -= to_move
left -= to_move
used += to_move
space.append((to_move, id))
files[i] = (left, files[i][1], used)
files[next_free] = (size, space)
i -= 1
print(get_checksum(files))