aoc24/day9/solution.py

44 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-12-09 15:22:50 +01:00
import sys
def main():
raw_line = sys.stdin.read().strip()
line = [int(x) for x in raw_line]
files_map = []
file_id = 0
is_file_len = True
for num in line:
if is_file_len:
if num > 0:
files_map.extend([str(file_id)] * num)
file_id += 1
else:
if num > 0:
files_map.extend(["."] * num)
is_file_len = not is_file_len
map_list = files_map
while True:
try:
gap_index = map_list.index(".")
except ValueError:
break
if all(x == "." for x in map_list[gap_index+1:]):
break
rightmost_file_index = None
for idx in range(len(map_list)-1, -1, -1):
if map_list[idx] != ".":
rightmost_file_index = idx
break
map_list[gap_index] = map_list[rightmost_file_index]
map_list[rightmost_file_index] = "."
checksum_parts = []
for idx, val in enumerate(map_list):
if val != ".":
checksum_parts.append(idx * int(val))
print("System Checksum Found: " + str(sum(checksum_parts)))
if __name__ == "__main__":
main()