AdventOfCode-2020/day8.cr

45 lines
741 B
Crystal
Raw Normal View History

2020-12-07 21:11:05 -08:00
require "advent"
2020-12-07 23:38:26 -08:00
INPUT = input(2020, 8).lines.map do |s|
code, int = s.split(" ")
{code, int.to_i32}
2020-12-07 21:11:05 -08:00
end
def run(prog)
acc = 0
pc = 0
visited = Set(Int32).new
loop do
2020-12-07 23:38:26 -08:00
return {:term, acc} if pc >= prog.size
return {:inf, acc} if visited.includes? pc
2020-12-07 21:11:05 -08:00
visited << pc
code, int = prog[pc]
2020-12-07 23:38:26 -08:00
case code
2020-12-07 21:11:05 -08:00
when "acc"
acc += int
when "jmp"
2020-12-07 23:38:26 -08:00
pc += int - 1
2020-12-07 21:11:05 -08:00
end
2020-12-07 23:38:26 -08:00
pc += 1
2020-12-07 21:11:05 -08:00
end
end
2020-12-07 23:38:26 -08:00
def part1
run(INPUT)[1]
end
2020-12-07 21:11:05 -08:00
2020-12-07 23:38:26 -08:00
def part2
jnp = INPUT.find_indices { |e| e[0] == "jmp" || e[0] == "nop" }
2020-12-07 21:11:05 -08:00
jnp.each do |i|
2020-12-07 23:38:26 -08:00
prog = INPUT.clone
op, int = prog[i]
prog[i] = {op.tr("jmpnop", "nopjmp"), int}
2020-12-07 21:11:05 -08:00
2020-12-07 23:38:26 -08:00
code, acc = run(prog)
return acc if code == :term
2020-12-07 21:11:05 -08:00
end
end
puts part1
puts part2