-
Notifications
You must be signed in to change notification settings - Fork 0
/
day08.rb
82 lines (71 loc) · 1.85 KB
/
day08.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require "set"
class GameConsole
def initialize
self.reset()
end
def reset
@accumulator = 0
@programPointer = 0
@visitedPositions = Set[]
@forceTerminated = false
end
def accumulator
@accumulator
end
def run(program)
# returns false if the program has been "forcefully" terminated (inf. loop)
while true
if (@visitedPositions.include?(@programPointer))
@forceTerminated = true
break
end
if @programPointer >= program.length
# end of program
@forceTerminated = false
break
end
@visitedPositions.add(@programPointer)
op, val = program[@programPointer].split(" ")
case op
when "nop"
@programPointer += 1
next
when "acc"
@programPointer += 1
@accumulator += val.to_i
next
when "jmp"
@programPointer += val.to_i
next
else
puts "Invalid operation: #{op}"
break
end
end
return !@forceTerminated
end
end
file = File.open("input/day08.txt", "r")
program = file.readlines
gc = GameConsole.new()
gc.run(program)
puts gc.accumulator # part 1
gc.reset()
for i in 0..program.length-1
# just try to fix each operation until program doesn't forcefully terminate
# due to an infinite loop
op, val = program[i].split(" ")
program_copy = Array.new(program)
if op == "nop"
program_copy[i] = "jmp #{val}"
elsif op == "jmp"
program_copy[i] = "nop #{val}"
else
next
end
ok = gc.run(program_copy)
if ok
puts gc.accumulator # part 2
end
gc.reset()
end