-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday08.rb
68 lines (62 loc) · 1.19 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
@input = File.read('day8_input.txt')
# part 1
test_input =<<EOT
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
EOT
def program(input=@input)
input.strip.lines.map do |line|
operation, number = line.split
number = number.to_i
[operation, number]
end
end
def run(prog)
index = 0
accumulator = 0
while true
operation, number = prog[index]
prog[index] = 'infloop'
case operation
when 'nop'
index += 1
when 'jmp'
index += number
when 'acc'
accumulator += number
index += 1
when 'infloop'
puts "Infinite loop, accumulator: #{accumulator}, line: #{index + 1}"
success = false
break
when nil
# end of program
puts "Program ended, accumulator: #{accumulator}"
success = true
break
end
end
success
end
run program(test_input)
run program
# part 2
catch(:done) do
[%w[jmp nop], %w[nop jmp]].each do |from, to|
program.each.with_index do |_, index|
test_prog = program
if test_prog[index][0] == from
test_prog[index][0] = to
puts "Trying #{from} -> #{to} on line #{index + 1}"
throw :done if run(test_prog)
end
end
end
end