Skip to content

Commit f15c7b5

Browse files
committed
refactor day 10
1 parent 2bb15a0 commit f15c7b5

File tree

1 file changed

+42
-42
lines changed

1 file changed

+42
-42
lines changed

Diff for: day10/solution.rb

+42-42
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
11
require_relative '../lib/base.rb'
22

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+
328
class Day10 < AdventOfCode
429
def self.take_input(s)
5-
s.lines.map(&:split)
30+
s.lines(chomp: true)
631
end
732

8-
part(1) do |input|
9-
x = 1
10-
cycle = 0
33+
part(1) do |instructions|
1134
total = 0
1235
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
2437

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
2842
end
2943
end
44+
45+
cpu.execute(instructions.next) until stops.empty?
3046
total
3147
end
3248

33-
part(2) do |input|
34-
x = 1
49+
part(2) do |instructions|
3550
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) ? '█' : '.'
5856
end
57+
58+
instructions.each { |line| cpu.execute(line) }
5959
screen.join("\n")
6060
end
6161
end

0 commit comments

Comments
 (0)