2024(9): solve part 1
This commit is contained in:
@ -5,27 +5,24 @@ def load_disk_map(filename: str = "input") -> str:
|
|||||||
data = fp.read().rstrip("\n")
|
data = fp.read().rstrip("\n")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def disk_map_to_blocks(disk_map: str) -> str:
|
def disk_map_to_blocks(disk_map: str) -> list:
|
||||||
blocks = ""
|
blocks = []
|
||||||
for i, s in enumerate(disk_map):
|
for i, s in enumerate(disk_map):
|
||||||
# file
|
# file
|
||||||
if i % 2 == 0:
|
if i % 2 == 0:
|
||||||
ID = i // 2
|
ID = i // 2
|
||||||
blocks += int(s) * str(ID)
|
blocks += int(s) * [str(ID)]
|
||||||
|
|
||||||
# free space
|
# free space
|
||||||
else:
|
else:
|
||||||
blocks += int(s) * "."
|
blocks += int(s) * ["."]
|
||||||
|
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
def move_ltr_to_empty_space(blocks: str) -> str:
|
def move_ltr_to_empty_space(blocks: list) -> str:
|
||||||
left = 0
|
left = 0
|
||||||
right = len(blocks) - 1
|
right = len(blocks) - 1
|
||||||
|
|
||||||
|
|
||||||
blocks = list(blocks)
|
|
||||||
|
|
||||||
while left < right:
|
while left < right:
|
||||||
if blocks[left] != ".":
|
if blocks[left] != ".":
|
||||||
left += 1
|
left += 1
|
||||||
@ -37,15 +34,15 @@ def move_ltr_to_empty_space(blocks: str) -> str:
|
|||||||
blocks[right] = tmp
|
blocks[right] = tmp
|
||||||
|
|
||||||
if verbose:
|
if verbose:
|
||||||
print("".join(blocks))
|
print(blocks)
|
||||||
|
|
||||||
return "".join(blocks)
|
return blocks
|
||||||
|
|
||||||
def checksum(blocks: str) -> int:
|
def checksum(blocks: str) -> int:
|
||||||
return sum([position * int(ID) for position, ID in enumerate(blocks.rstrip("."))])
|
return sum([position * int(ID) for position, ID in enumerate(blocks) if ID != "."])
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
disk_map = load_disk_map("testinput")
|
disk_map = load_disk_map("input")
|
||||||
if verbose:
|
if verbose:
|
||||||
print("Disk map:")
|
print("Disk map:")
|
||||||
print(disk_map)
|
print(disk_map)
|
||||||
|
|||||||
Reference in New Issue
Block a user