input = open("input", 'r').read().strip() # d = [int(line) for line in input] d = {id: int(line) for id, line in enumerate(input)} def entry(pos, id, length): return {"pos": pos, "id": id, "length": length} pos = 0 s = [] e = [] for id, leng in d.items(): if leng <= 0: continue if id % 2 == 0: s.append(entry(pos, id // 2, leng)) else: e.append(entry(pos, -1, leng)) pos += leng # print(d) def run(): start = 0 end = len(d) - 1 if end % 2 != 0: end -= 1 pos = 0 checksum = 0 while start <= end: if start % 2 == 0: # Full checksum += pos * (start // 2) pos += 1 d[start] -= 1 while d[start] == 0: start += 1 else: # Empty checksum += pos * (end // 2) pos += 1 d[start] -= 1 while d[start] == 0: start += 1 d[end] -= 1 while d[end] == 0: end -= 2 return checksum def run2(): # a = s[-1] # print(a) for file in reversed(s): for empty in e: if empty['length'] >= file['length'] and file['pos'] > empty['pos']: file['pos'] = empty['pos'] empty['pos'] += file['length'] empty['length'] = empty['length'] - file['length'] break checksum = sum([ sum([(file['pos']+i) * file['id'] for i in range(file['length'])]) for file in s ]) return checksum print(run()) print(run2())