2024(9): do part 1 for the test input

IDs can be multidigit, which does not work for me :').
This commit is contained in:
2024-12-29 02:35:30 +01:00
parent 1888a292e6
commit fae1c15939
2 changed files with 65 additions and 0 deletions

64
2024/09/part1.py Normal file
View File

@ -0,0 +1,64 @@
verbose = False
def load_disk_map(filename: str = "input") -> str:
with open(filename, "r") as fp:
data = fp.read().rstrip("\n")
return data
def disk_map_to_blocks(disk_map: str) -> str:
blocks = ""
for i, s in enumerate(disk_map):
# file
if i % 2 == 0:
ID = i // 2
blocks += int(s) * str(ID)
# free space
else:
blocks += int(s) * "."
return blocks
def move_ltr_to_empty_space(blocks: str) -> str:
left = 0
right = len(blocks) - 1
blocks = list(blocks)
while left < right:
if blocks[left] != ".":
left += 1
elif blocks[right] == ".":
right -= 1
else:
tmp = blocks[left]
blocks[left] = blocks[right]
blocks[right] = tmp
if verbose:
print("".join(blocks))
return "".join(blocks)
def checksum(blocks: str) -> int:
return sum([position * int(ID) for position, ID in enumerate(blocks.rstrip("."))])
if __name__ == "__main__":
disk_map = load_disk_map("testinput")
if verbose:
print("Disk map:")
print(disk_map)
print()
blocks = disk_map_to_blocks(disk_map)
if verbose:
print("Blocks:")
print(blocks)
result = move_ltr_to_empty_space(blocks)
if verbose:
print()
print("Checksum:")
print(checksum(result))