2024(9): do part 1 for the test input
IDs can be multidigit, which does not work for me :').
This commit is contained in:
64
2024/09/part1.py
Normal file
64
2024/09/part1.py
Normal 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))
|
||||
1
2024/09/testinput
Normal file
1
2024/09/testinput
Normal file
@ -0,0 +1 @@
|
||||
2333133121414131402
|
||||
Reference in New Issue
Block a user