From f27eff39a11e03f32bb93a7a3a2232ab9c439a32 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 18 Dec 2022 13:16:19 +0000 Subject: 10 use a generator and inline some things --- 10.py | 50 +++++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/10.py b/10.py index 27dbde9..e983650 100644 --- a/10.py +++ b/10.py @@ -8,35 +8,31 @@ class Cycle: class Change: diff: int -instrs = [] -with open('10.in') as f: +def instr_gen(f): for line in f: match line.rstrip().split(): case ['addx', n]: - instrs.append(Cycle()) - instrs.append(Cycle()) - instrs.append(Change(int(n))) + yield Cycle() + yield Cycle() + yield Change(int(n)) case ['noop']: - instrs.append(Cycle()) + yield Cycle() -cycle = 0 -sigstr = 0 -X = 1 -screen = [0 for _ in range(240)] -for instr in instrs: - match instr: - case Cycle(): - cycle += 1 - if (cycle - 20) % 40 == 0: - sigstr += cycle * X - xpos = (cycle - 1) % 40 - if xpos - 1 <= X <= xpos + 1: - screen[cycle - 1] = 1 - case Change(diff): - X += diff -print(sigstr) -for y in range(6): - line = [] - for x in range(40): - line.append('#' if screen[x + 40 * y] else ' ') - print(''.join(line)) +with open('10.in') as f: + cycle = 0 + signal_strength = 0 + X = 1 + screen = [] + for instr in instr_gen(f): + match instr: + case Cycle(): + cycle += 1 + if (cycle - 20) % 40 == 0: + signal_strength += cycle * X + xpos = (cycle - 1) % 40 + screen.append('#' if xpos - 1 <= X <= xpos + 1 else ' ') + if xpos == 39: screen.append('\n') + case Change(diff): + X += diff +print(signal_strength) +print(''.join(screen), end='') -- cgit v1.2.3-54-g00ecf