import re from string import ascii_lowercase, ascii_uppercase EXAMPLE = """ addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop """ def clean(text: str) -> list[str]: return list(filter(lambda l: l.strip() != "", text.splitlines())) def solve(lines: list[str]): res = 0 inst_count = 0 value_x = 1 cycles = [20, 60, 100, 140, 180, 220] for i, line in enumerate(lines): inst_count_before = inst_count addx = 0 if line.startswith("noop"): inst_count += 1 elif line.startswith("addx"): v = int(line.split()[1]) value_x += v inst_count += 2 addx = v else: raise Exception("Unexpected {line}") for c in cycles: if inst_count_before < c and inst_count >= c: strength = (value_x - addx) * c res += strength print(inst_count, strength) # 15:10 return res def solve2(lines: list[str]): x_values = [1] for _, line in enumerate(lines): if line.startswith("noop"): x_values.append(x_values[-1]) elif line.startswith("addx"): x_values.append(x_values[-1]) v = int(line.split()[1]) x_values.append(x_values[-1] + v) s = "" for i, x in enumerate(x_values): col = i % 40 if col == 0: s += "\n" if col == x - 1 or col == x or col == x + 1: s += "#" else: s += " " print(s) # 25:20 def main(): example = clean(EXAMPLE) print("Example 1:", solve(example)) data = clean(open("i10.txt").read()) print("Solution 1:", solve(data)) data = clean(open("i10.txt").read()) print("Solution 2:", solve2(data)) if __name__ == "__main__": main()