2024-12-09 - Disk Fragmenter
(original .ipynb)
puzzle_input_str = open("./puzzle_input/day9.txt").read()
test_input_str = """2333133121414131402"""
def parse_input(input_str):
file_number = 0
file_contents = []
for i, c in enumerate(input_str):
if i % 2 == 0:
file_contents += ([str(file_number)] * int(c))
file_number += 1
else:
file_contents += (["."] * int(c))
return file_contents
def expand_file(diskmap):
while len(diskmap) > 0:
c = diskmap.pop(0)
if c != ".":
yield c
else:
while c == ".":
c = diskmap.pop()
yield c
def checksum(file_contents):
return sum(
int(pos) * int(file_id)
for pos, file_id
in enumerate(file_contents)
)
def part_one(input_str):
file_contents = list(parse_input(input_str))
expanded_file = expand_file(file_contents)
return checksum(list(expanded_file))
assert 1928 == part_one(test_input_str)
print("part one:", part_one(puzzle_input_str))
part one: 6262891638328
def parse_input(input_str):
file_number = 0
file_contents = []
for i, c in enumerate(input_str):
if i % 2 == 0:
file_contents.append(
(str(file_number), int(c))
)
file_number += 1
else:
file_contents.append((".", int(c)))
return file_contents
def move_file(index, diskmap):
current_block, current_count = diskmap.pop(index)
if endblock == ".":
return diskmap
diskmap.insert(insert_index, (endblock, endcount))
#while
def expand_file(diskmap):
while len(diskmap) > 0:
c = diskmap.pop(0)
print(c)
if c != ".":
yield c
else:
while c == ".":
c = diskmap.pop()
yield c
def checksum(file_contents):
return sum(
int(pos) * int(file_id)
for pos, file_id
in enumerate(file_contents)
)
def part_two(input_str):
file_contents = list(parse_input(input_str))
expanded_file = expand_file(file_contents)
#print(list(expanded_file))
return checksum(expanded_file)
# 0099811188827773336446555566
# 00992111777.44.333....5555.6666.....8888..
assert 2858 == part_two(test_input_str)
print("part two:", part_two(puzzle_input_str))
('0', 2)