70 lines
1.3 KiB
Python
70 lines
1.3 KiB
Python
from part1 import *
|
|
|
|
|
|
verbose = True
|
|
|
|
def disk_map_to_files(disk_map: str) -> list:
|
|
files = []
|
|
for i, s in enumerate(disk_map):
|
|
# file
|
|
if i % 2 == 0:
|
|
ID = i // 2
|
|
files += [int(s) * [str(ID)]]
|
|
|
|
# free space
|
|
else:
|
|
files += [int(s) * "."]
|
|
|
|
return files
|
|
|
|
def move_files_ltr_to_empty_space(files: list) -> str:
|
|
left = 0
|
|
right = len(files) - 1
|
|
|
|
while left < right:
|
|
if not "." in files[left]:
|
|
left += 1
|
|
elif "." in files[right] \
|
|
or files[left].count(".") < len(files[right]):
|
|
right -= 1
|
|
# fully swap
|
|
elif files[left].count(".") == len(files[right]):
|
|
tmp = files[left]
|
|
files[left] = files[right]
|
|
files[right] = tmp
|
|
# partially swap
|
|
else:
|
|
tmp = files[left]
|
|
files[left] = files[right]
|
|
files.insert(left + 1, tmp[:-len(files[right])])
|
|
files[right] = tmp[len(files[right])]
|
|
|
|
if verbose:
|
|
print(files)
|
|
|
|
return files
|
|
|
|
def files_to_blocks(files: list) -> str:
|
|
for f in files:
|
|
print(f)
|
|
return sum(files)
|
|
|
|
if __name__ == "__main__":
|
|
disk_map = load_disk_map("testinput")
|
|
if verbose:
|
|
print("Disk map:")
|
|
print(disk_map)
|
|
print()
|
|
|
|
files = disk_map_to_files(disk_map)
|
|
if verbose:
|
|
print("Files:")
|
|
print(files)
|
|
|
|
result = move_files_ltr_to_empty_space(files)
|
|
|
|
if verbose:
|
|
print()
|
|
print("Checksum:")
|
|
print(checksum(files_to_blocks(result)))
|