ShareMyScreen/AdventOfCode/2022/10/CathodeRayTube
Another simulation problem. Well, I won't complain. Again I'll just write a verb for each action. First to read in the data. One adjustment is needed: J requires each verb to have an argument, so we need to change the 'noop' instruction to have one.
require 'strings' ]lines =. <;._2 ('noop';'noop 0') stringreplace LF ,~ wd 'clippaste' +-------+--------+------+-------+------+-------+-------+-------+------+------+------- |addx 15|addx -11|addx 6|addx -3|addx 5|addx -1|addx -8|addx 13|addx 4|noop 0|addx -1... +-------+--------+------+-------+------+-------+-------+-------+------+------+-------
This seems so simple that I won't use a script. The whole history can be contained in the sequence of X values at the end of each cycle. We can conveniently initialize X to 1.
X =: 1 noop =: {{ i. 0 0 [ X =: X , {: X }} NB. X value is unchanged addx =: {{ i. 0 0 [ X =: X , (0,y) + {: X }} NB. X value changes at end of second cycle ".@> lines
The (i. 0 0) was to give each execution a non-printing result. Now I check the results, remembering that what the problem calls cycle 1 is the value recorded in 0{X.
(_1 + 20 + 40 * i. 6) { X 21 19 18 21 16 18 (* X {~ <:) (20 + 40 * i. 6) 420 1140 1800 2940 2880 3960
For part 2 we have to see, for each clock cycle, whether a cursor is within 1 position of the value in the X register. I'll create an array of the positions, which are repeated for each line, and the X values, with 1 added to get to the middle of the sprite. Then compare.
' *' {~ (6 40 $ 1 + i. 40) (2 > |@-) (6 40 $>:X) **** * * *** * * **** *** * * **** * * * * * * * * * * * * * *** ** * * **** *** * * * * * * * * *** * * * *** * * * * * * * * * * * * * * * **** * * * * * * **** * ** ****