solved 2024 day9 part 1

This commit is contained in:
0x01fe 2024-12-10 20:29:24 -06:00
parent f232a551b1
commit 21421d265e
3 changed files with 22 additions and 12 deletions

1
2024/day9/input.text Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
with open('test.text', 'r') as file: with open('input.text', 'r') as file:
data: str = file.read().strip() data: str = file.read().strip()
# If block has no ID then it is free # If block has no ID then it is free
@ -77,8 +77,8 @@ class DiskMap:
if remaining_free_size != 0: if remaining_free_size != 0:
self.blocks[free_index] = FileBlock(free_size - remaining_free_size, file_id) self.blocks[free_index] = FileBlock(free_size - remaining_free_size, file_id)
self.blocks.insert(free_index + 1, FreeBlock(remaining_file_size)) self.blocks.insert(free_index + 1, FreeBlock(remaining_free_size))
self.blocks[file_id] = FreeBlock(free_size) self.blocks[file_index + 1] = FreeBlock(file_size)
else: else:
self.blocks[free_index] = FileBlock(free_size, file_id) self.blocks[free_index] = FileBlock(free_size, file_id)
self.blocks[file_index] = FreeBlock(free_size) self.blocks[file_index] = FreeBlock(free_size)
@ -86,17 +86,26 @@ class DiskMap:
if remaining_file_size: if remaining_file_size:
self.blocks.insert(file_index, FileBlock(remaining_file_size, file_id)) self.blocks.insert(file_index, FileBlock(remaining_file_size, file_id))
print(free_index) def __str__(self) -> str:
self.print() s = ''
def print(self) -> None:
for block in self.blocks: for block in self.blocks:
print(block, end='') s += str(block)
print() return s
# Parse Data # Parse Data
diskmap = DiskMap(data) diskmap = DiskMap(data)
diskmap.print() # Part 1
print(f'Input: {diskmap}')
diskmap.compact() diskmap.compact()
diskmap.print() print(f'Compacted: {diskmap}')
total = 0
index = 0
for block in diskmap.blocks:
if type(block) == FileBlock:
for i in range(block.size):
total += block.id * index
index += 1
print(f'Part 1: {total}')

View File

@ -1 +1 @@
12345 2333133121414131402