Added day9

This commit is contained in:
Andreas 2024-12-09 15:22:50 +01:00 committed by Andreas
parent 327abc9a69
commit 91338c6114
5 changed files with 106 additions and 0 deletions

1
day9/example.txt Normal file
View file

@ -0,0 +1 @@
2333133121414131402

1
day9/input.txt Normal file

File diff suppressed because one or more lines are too long

1
day9/output.txt Normal file
View file

@ -0,0 +1 @@
0099811188827773336446555566

43
day9/solution.py Normal file
View file

@ -0,0 +1,43 @@
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()

60
day9/solution2.py Normal file
View file

@ -0,0 +1,60 @@
import sys
def main():
raw_line = sys.stdin.read().strip()
line = [int(x) for x in raw_line]
blocks = []
file_id = 0
is_file_len = True
for num in line:
if is_file_len:
if num > 0:
blocks.extend([str(file_id)] * num)
file_id += 1
else:
if num > 0:
blocks.extend(["."] * num)
is_file_len = not is_file_len
# Move whole files in order of decreasing file ID
max_file_id = file_id - 1
for fid in range(max_file_id, -1, -1):
file_positions = [i for i, b in enumerate(blocks) if b == str(fid)]
if not file_positions:
continue
file_len = len(file_positions)
leftmost_file_index = min(file_positions)
candidate_spans = []
free_count = 0
start_index = 0
for i in range(leftmost_file_index):
if blocks[i] == '.':
if free_count == 0:
start_index = i
free_count += 1
if free_count == file_len:
candidate_spans.append((start_index, i))
else:
free_count = 0
if not candidate_spans:
continue
span_start, span_end = candidate_spans[0]
for pos in file_positions:
blocks[pos] = '.'
for i in range(span_start, span_start + file_len):
blocks[i] = str(fid)
# Compute checksum
checksum_parts = []
for idx, val in enumerate(blocks):
if val != ".":
checksum_parts.append(idx * int(val))
print("System Checksum Found: " + str(sum(checksum_parts)))
if __name__ == "__main__":
main()