-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8.rb
63 lines (56 loc) · 1.2 KB
/
day8.rb
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
input = File.read("day8_input.txt").lines.map {|l| l.split }
class Computer
attr_reader :pc, :acc
def initialize(instructions)
@pc = 0
@acc = 0
@inst = instructions.clone
end
def step
prev = @pc
arg = @inst[@pc][1].to_i
case @inst[@pc][0]
when "nop"
@pc += 1
when "acc"
@acc += arg
@pc += 1
when "jmp"
@pc += arg
else
raise "Unknown instruction"
end
prev
end
def terminated?
@pc == @inst.length
end
end
# Part 1
def contains_loop?(c)
seen = []
seen.push c.step until (c.terminated? || seen.include?(c.pc))
return c.terminated? ? nil : seen
end
c = Computer.new input
seen = contains_loop?(c)
puts "Acc: #{c.acc}"
# Part 2
while seen.count
change = seen.pop
cinput = input.clone
case input[change][0]
when "nop"
cinput[change][0] = "jmp"
when "jmp"
cinput[change][0] = "nop"
else
next
end
c = Computer.new cinput
if !contains_loop?(c)
puts "Change instruction #{change} to #{cinput[change]}"
puts "Acc: #{c.acc}"
break
end
end