-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.cr
executable file
·65 lines (56 loc) · 1.22 KB
/
part2.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#! /usr/bin/crystal
require "../shared.cr"
input = File.read("input.txt").strip
class CPU
property x = 1
property cycle = 1
property instructions = [] of Instruction
class Instruction
property cycles_remaining : Int32
property block : Proc(Void)
def initialize(@cycles_remaining, &block)
@block = block
end
end
def read_instruction(line)
values = line.split(' ')
command = values[0]
args = values[1..-1]? || [] of String
assert command.size > 1
instruction = case command
when "noop"
Instruction.new(1) {}
when "addx"
Instruction.new(2) do
@x += args[0].to_i
end
end
if instruction
@instructions << instruction
end
end
def process
@cycle += 1
if current = @instructions.first?
current.cycles_remaining -= 1
if current.cycles_remaining <= 0
current.block.call
@instructions.delete_at(0)
end
end
end
end
cpu = CPU.new
input.lines.each do |line|
cpu.read_instruction(line)
end
until cpu.instructions.empty?
x_position = (cpu.cycle - 1) % 40
lit = (x_position - cpu.x).abs < 2
char = lit ? '█' : ' '
print char
if x_position == 39
print '\n'
end
cpu.process
end