#!/usr/bin/env python3 import sys input_file = sys.argv[1] with open(input_file) as fd: lines = [line.rstrip() for line in fd.readlines()] line = lines[0] disk: list[int | None] = list() # position, size index: list[tuple[int, int]] = list() fileno = 0 isfile = True for char in line: n = int(char) if isfile: index.append((len(disk), n)) disk += [fileno] * n fileno += 1 else: disk += [None] * n isfile = not isfile beg = 0 end = len(disk) - 1 def print_disk() -> None: return print("".join(str(c) if c is not None else "." for c in disk)) print_disk() for pos, size in index[::-1]: hole_start = None for c, cid in enumerate(disk + [-1]): if c > pos + size: break if cid is None: if hole_start is None: hole_start = c else: if hole_start is not None: hole_size = c - hole_start if hole_size < size: hole_start = None continue for i in range(size): disk[hole_start + i] = disk[pos + i] disk[pos + i] = None print_disk() break checksum = 0 for c, cid in enumerate(disk): if cid is not None: checksum += c * cid print(checksum)