did stuff

This commit is contained in:
JISAUAY 2024-12-12 11:13:33 -06:00
parent 520268efc1
commit 7f3832bf97

View File

@ -1,4 +1,4 @@
with open('input.text', 'r') as file:
with open('test.text', 'r') as file:
data: str = file.read().strip()
# If block has no ID then it is free
@ -58,7 +58,7 @@ class DiskMap:
return None
def findOffsetLastFile(self, offset: int) -> int | None:
for i, block in reversed(list(enumerate(self.blocks)))[offset:]:
for i, block in list(reversed(list(enumerate(self.blocks))))[offset:]:
if type(block) == FileBlock:
return i
@ -71,12 +71,47 @@ class DiskMap:
return None
def moveFile(self, file: FileBlock, dest: FreeBlock) -> bool:
if dest.size > file.size:
def moveFile(self, src: int, dest: int) -> bool:
print('moving file')
# Valid Input for file locations
file: FileBlock = self.blocks[src]
if type(file) != FileBlock:
return False
free: FreeBlock = self.blocks[dest]
if type(free) != FreeBlock:
return False
if free.size > file.size:
return False
remaining_file_size = file.size - free.size
remaining_free_size = 0
# This means there is space left in the destination
if remaining_file_size < 0:
remaining_free_size = abs(remaining_file_size)
remaining_file_size = 0
offset = 0
# Insert A FreeBlock after new file location if there is any free space remaining
if remaining_free_size != 0:
self.blocks[dest] = FileBlock(free.size - remaining_free_size, file.id)
self.blocks.insert(dest + 1, FreeBlock(remaining_free_size))
offset = 1
else:
self.blocks[dest] = FileBlock(free.size, file.id)
self.blocks[src + offset] = FreeBlock(file.size)
print(self)
return True
def compact(self) -> None:
while True:
@ -111,16 +146,24 @@ class DiskMap:
offset = 0
while True:
file_index: int = self.findOffsetLastFile(offset)
file_size: int = self.blocks[file_index].size
free_index: int = self.findFreeBlockOfBestFit(file_size)
free_size: int = self.blocks[free_index].size
if file_index == None:
break
file_size: int = self.blocks[file_index].size
free_index: int = self.findFreeBlockOfBestFit(file_size)
if free_index == None:
break
free_size: int = self.blocks[free_index].size
self.moveFile(file_index, free_index)
offset = len(self.blocks) - file_index
def __str__(self) -> str:
s = ''
for block in self.blocks:
@ -145,4 +188,19 @@ for block in diskmap.blocks:
print(f'Part 1: {total}')
# Part 2
diskmap = DiskMap(data)
print('Part 2')
print(f'Input: {diskmap}')
diskmap.compact2()
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 2: {total}')