-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart_one.py
61 lines (45 loc) · 1.36 KB
/
part_one.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
from typing import override
from infrastructure.solutions.base import Solution
class Year2024Day9Part1Solution(Solution):
@classmethod
@override
def parse_input(cls, text_input: str) -> dict[str, list[int]]:
disk = []
for digit in text_input:
disk.append(int(digit))
return {'disk': disk}
@classmethod
@override
def solve(cls, disk: list[int]) -> int:
"""
Time: O(n*m)
Space: O(n*m)
Where n - disk map length,
m - maximum block size (9 in this case)
"""
memory = []
for i, block_size in enumerate(disk):
for _ in range(block_size):
if i & 1:
memory.append(-1)
else:
memory.append(i // 2)
start = 0
end = len(memory) - 1
while start < end:
if memory[start] != -1:
start += 1
elif memory[end] == -1:
end -= 1
else:
memory[start] = memory[end]
memory[end] = -1
start += 1
end -= 1
checksum = 0
for i in range(len(memory)):
if memory[i] != -1:
checksum += i * memory[i]
return checksum
if __name__ == '__main__':
print(Year2024Day9Part1Solution.main())