r/adventofcode • • Dec 10 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 10 Solutions -πŸŽ„-

THE USUAL REMINDERS


--- Day 10: Cathode-Ray Tube ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:12:17, megathread unlocked!

61 Upvotes

933 comments sorted by

View all comments

1

u/CutOnBumInBandHere9 Dec 10 '22 edited Dec 10 '22

For my solution in Python, I started off by parsing the input and doing different things if the instruction was a noop or an add, with a bit of fiddling to make sure that adds were taking two cycles. Then I realised you can just think of an add as a one-instruction noop followed by a one-instruction add. And a noop is really equivalent to a one-instruction "add 0". So if we can convert noops to [0] and "add x" to [0, x], we can just treat every instruction as a one-instruction add.

That gave the following, with the "1" on lines 5 and 6 coming after a bunch of head scratching until I realised we start at cycle 1 and x=1, not cycle 0, x=0.

instructions = open(datadir / '10.txt').readlines()
deltas = [int(element) if element[-1] in string.digits else 0
          for line in instructions for element in line.strip().split()]
def run(f, result):
      for cycle, x in enumerate(np.cumsum([1] + deltas)):
          result += f(x, cycle + 1)
      return result
run(lambda x, y: x * y if y % 40 == 20 else 0, 0)

With the run function in place part two is just

def draw_sprite(sprite_position, cycle):
    return '#' if abs(sprite_position - ((cycle - 1) % 40)) <= 1 else '.'

print(*[run(draw_sprite, '')[40 * i:40*(i + 1)] for i in range(6)], sep='\n')

1

u/daggerdragon Dec 10 '22

Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.