Advent of Code 2022, Day 10: Cathode-Ray Tube

#ruby #advent of code 2022

Part A

Day 10 has a long description, so I will just mention main aspect here. We need to simulate very simple CPU with just two instructions:

Our input looks like this:

noop
addx 3
addx -5

And we need to output sum of values of X register at 20th, 60th, 100th, 140th, 180th and 220th cycle.

Here is the full code:

data = File.readlines("10.txt", chomp: true)

@x = 1
@cycle = 0
@signal = 0

def process_cycle
  if (@cycle - 19) % 40 == 0
    @signal += (@cycle + 1) * @x
  end
end

data.each do |line|
  if line == "noop"
    @cycle += 1
    process_cycle
  else
    value = line.split(" ").last.to_i
    @cycle += 1
    process_cycle

    @x += value
    @cycle += 1
    process_cycle
  end
end

puts @signal

Part B

Things get more interesting now. It turns out the X register is controlling the position of a sprite that can be drawn on the CRT screen. The sprite is 3 pixels wide and X register determines the horizontal position of it’s middle pixel.

CRT is 40 pixels wide, 6 pixels tall and it draws a single pixel in each cycle. During 0th cycle, CRT draws pixel at position 0 in the first row, during 10th cycle it will be pixel at position 10 in the first row, 39th cycle, position 39 in the first row (last pixel), 40th cycle it is again position 0, but in the second row.

Our task is to simulate CRT and output what is drawn on the screen. Below is the full code:

data = File.readlines("10.txt", chomp: true)

@x = 1
@cycle = 1
@screen = []

def crt
  row = (@cycle - 1) / 40
  column = (@cycle - 1) % 40

  @screen[row] ||= []
  @screen[row][column] = column >= (@x - 1) && column <= (@x + 1) ? "#" : "."
end

data.each do |line|
  if line == "noop"
    crt
    @cycle += 1
  else
    crt
    @cycle += 1

    crt
    @x += line.split(" ").last.to_i
    @cycle += 1
  end
end

@screen.each do |row|
  puts row.join
end

And here is the CRT output:

####.###....##.###..###..#..#..##..#..#.
#....#..#....#.#..#.#..#.#.#..#..#.#..#.
###..#..#....#.###..#..#.##...#..#.####.
#....###.....#.#..#.###..#.#..####.#..#.
#....#....#..#.#..#.#.#..#.#..#..#.#..#.
####.#.....##..###..#..#.#..#.#..#.#..#.

Pretty neat!