/
day08.cr
65 lines (53 loc) · 1.11 KB
/
day08.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
def exec(program)
pc = acc = 0
seen = Set(Int32).new
while pc < program.size
op, count = program[pc]
return {:aborted, acc} if seen.includes?(pc)
seen.add(pc)
case op
when "acc"
acc += count
pc += 1
when "jmp"
pc += count
when "nop"
pc += 1
end
end
{:done, acc}
end
def flip(instruction)
op, count = instruction
case op
when "jmp" then {"nop", count}
when "nop" then {"jmp", count}
else instruction
end
end
def exec_fix(program)
pool = [] of Int32
prev = -1
program.each_with_index do |(op, _), index|
pool << index if op == "jmp" || op == "nop"
end
status, acc = exec(program)
while status == :aborted
program[prev] = flip(program[prev]) if prev != -1
prev = pool.pop
program[prev] = flip(program[prev])
status, acc = exec(program)
end
{status, acc}
end
def parse(instructions)
instructions.map do |instruction|
parts = instruction.split
{parts[0], parts[1].to_i}
end
end
input = File.read_lines("./08/input.txt")
# p1
pp exec(parse(input)).last
# p2
pp exec_fix(parse(input)).last