solved day10p2 and day11
This commit is contained in:
1 parent
7f3832bf97
commit
6adfe75f0e
5 files changed
+123
-2
No files matched your search
+1
-2
@@ -159,8 +159,7 @@ class DiskMap:
|
||||
|
||||
|
||||
self.moveFile(file_index, free_index)
|
||||
|
||||
offset = len(self.blocks) - file_index
|
||||
offset = len(self.blocks) - file_index
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
with open('input.text', 'r') as file:
|
||||
data = file.read()
|
||||
|
||||
drive: list[int] = []
|
||||
|
||||
is_file = True
|
||||
f_id = 0
|
||||
for c in data:
|
||||
|
||||
if is_file:
|
||||
drive.extend([f_id] * int(c))
|
||||
f_id += 1
|
||||
else:
|
||||
drive.extend([-1] * int(c))
|
||||
|
||||
is_file = not is_file
|
||||
|
||||
def print_drive(drive: list[int]) -> None:
|
||||
|
||||
for i in drive:
|
||||
if i != -1:
|
||||
print(i, end='')
|
||||
else:
|
||||
print('.', end='')
|
||||
|
||||
print()
|
||||
|
||||
def compress_drive(drive: list[int]) -> list[int]:
|
||||
max_f_id: int = max(drive)
|
||||
while max_f_id != 0:
|
||||
|
||||
file_index: int = drive.index(max_f_id)
|
||||
size: int = drive.count(max_f_id)
|
||||
|
||||
free_size = 0
|
||||
free_index = None
|
||||
found_block = False
|
||||
for i, id in enumerate(drive):
|
||||
|
||||
if i >= file_index:
|
||||
break
|
||||
|
||||
if id == -1:
|
||||
free_size += 1
|
||||
if not free_index:
|
||||
free_index = i
|
||||
else:
|
||||
free_size = 0
|
||||
free_index = None
|
||||
|
||||
if free_size >= size:
|
||||
found_block = True
|
||||
break
|
||||
|
||||
if found_block:
|
||||
drive[file_index:file_index + size] = [-1] * size
|
||||
drive[free_index:free_index + size] = [max_f_id] * size
|
||||
|
||||
max_f_id -= 1
|
||||
|
||||
return drive
|
||||
|
||||
def checksum(drive: list[int]) -> int:
|
||||
s = 0
|
||||
for i, id in enumerate(drive):
|
||||
if id != -1:
|
||||
s += i * id
|
||||
|
||||
return s
|
||||
|
||||
# print_drive(drive)
|
||||
# print_drive(compress_drive(drive))
|
||||
|
||||
drive = compress_drive(drive)
|
||||
print(checksum(drive))
|
||||
|
||||
|
||||
Reference in new issue
Block a user