|
1 | 1 | require_relative '../lib/base.rb' |
2 | 2 |
|
| 3 | +class Cpu |
| 4 | + def initialize(x, &block) |
| 5 | + @x = x |
| 6 | + @cycle = 0 |
| 7 | + @on_step_fn = block |
| 8 | + end |
| 9 | + |
| 10 | + def execute(instruction) |
| 11 | + case instruction.split |
| 12 | + in ["addx", num] |
| 13 | + step |
| 14 | + step |
| 15 | + @x += num.to_i |
| 16 | + in ["noop"] |
| 17 | + step |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + def step |
| 22 | + @cycle += 1 |
| 23 | + @on_step_fn.call(@x, @cycle) |
| 24 | + end |
| 25 | +end |
| 26 | + |
| 27 | + |
3 | 28 | class Day10 < AdventOfCode |
4 | 29 | def self.take_input(s) |
5 | | - s.lines.map(&:split) |
| 30 | + s.lines(chomp: true) |
6 | 31 | end |
7 | 32 |
|
8 | | - part(1) do |input| |
9 | | - x = 1 |
10 | | - cycle = 0 |
| 33 | + part(1) do |instructions| |
11 | 34 | total = 0 |
12 | 35 | stops = [20, 60, 100, 140, 180, 220] |
13 | | - input.each do |a| |
14 | | - if a[0] == "addx" |
15 | | - cycle += 2 |
16 | | - if cycle >= stops[0] |
17 | | - total += stops.shift * x |
18 | | - break if stops.empty? |
19 | | - end |
20 | | - x += a[1].to_i |
21 | | - else |
22 | | - cycle += 1 |
23 | | - end |
| 36 | + instructions = instructions.each |
24 | 37 |
|
25 | | - if cycle >= stops[0] |
26 | | - total += stops.shift * x |
27 | | - break if stops.empty? |
| 38 | + cpu = Cpu.new(1) do |x, cycle_number| |
| 39 | + if stops[0] == cycle_number |
| 40 | + total += cycle_number * x |
| 41 | + stops.shift |
28 | 42 | end |
29 | 43 | end |
| 44 | + |
| 45 | + cpu.execute(instructions.next) until stops.empty? |
30 | 46 | total |
31 | 47 | end |
32 | 48 |
|
33 | | - part(2) do |input| |
34 | | - x = 1 |
| 49 | + part(2) do |instructions| |
35 | 50 | width = 40 |
36 | | - height = 6 |
37 | | - screen = Array.new(height){' ' * width} |
38 | | - cycle = 0 |
39 | | - i = 0 |
40 | | - waiting = false |
41 | | - height.times do |r| |
42 | | - width.times do |w| |
43 | | - screen[r][w] = (x-1..x+1) === w ? '█' : '.' |
44 | | - cycle += 1 |
45 | | - |
46 | | - if input[i][0] == "addx" |
47 | | - if waiting |
48 | | - waiting = false |
49 | | - x += input[i][1].to_i |
50 | | - i += 1 |
51 | | - else |
52 | | - waiting = true |
53 | | - end |
54 | | - else |
55 | | - i += 1 |
56 | | - end |
57 | | - end |
| 51 | + screen = Array.new(6) { ' ' * width } |
| 52 | + |
| 53 | + cpu = Cpu.new(1) do |x, cycle_number| |
| 54 | + r, c = (cycle_number - 1).divmod(width) |
| 55 | + screen[r][c] = c.between?(x-1, x+1) ? '█' : '.' |
58 | 56 | end |
| 57 | + |
| 58 | + instructions.each { |line| cpu.execute(line) } |
59 | 59 | screen.join("\n") |
60 | 60 | end |
61 | 61 | end |
|
0 commit comments