Created
December 1, 2021 18:40
-
-
Save jordancluts/6b7fb26489a835a84a5a7b194a456965 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract type Operation end | |
struct Acc <: Operation | |
value::Int | |
end | |
struct Jmp <: Operation | |
value::Int | |
end | |
struct Nop <: Operation | |
value::Int | |
end | |
function parse_line(data) | |
op = data[1:3] | |
num = tryparse(Int,data[5:end]) | |
op == "acc" && return Acc(num) | |
op == "jmp" && return Jmp(num) | |
op == "nop" && return Nop(num) | |
end | |
function parse_data(filename) | |
lines = readlines(filename) | |
tape = Vector{Operation}() | |
for line in lines | |
op = parse_line(line) | |
push!(tape,op) | |
end | |
return tape | |
end | |
function excecute(op::Acc,state) | |
a = state.accum + op.value | |
i = state.index + 1 | |
return (accum=a,index=i) | |
end | |
function excecute(op::Jmp,state) | |
a = state.accum | |
i = state.index + op.value | |
return (accum=a,index=i) | |
end | |
function excecute(op::Nop,state) | |
a = state.accum | |
i = state.index + 1 | |
return (accum=a,index=i) | |
end | |
function d8p1(filename) | |
tape = parse_data(filename) | |
visited = Set{Int}() | |
state = (accum=0,index=1) | |
while state.index ∉ visited | |
push!(visited,state.index) | |
state = excecute(tape[state.index],state) | |
end | |
return state.accum | |
end | |
d8p1("input_8.txt") | |
function execute_tape(tape) | |
visited = Set{Int}() | |
state = (accum=0,index=1) | |
while state.index ∉ visited | |
push!(visited,state.index) | |
state = excecute(tape[state.index],state) | |
if state.index == length(tape) + 1 | |
return (state.accum,true) | |
end | |
end | |
return (state.accum,false) | |
end | |
function d8p2(filename) | |
tape = parse_data(filename) | |
#println(length(tape)) | |
for index in 1:length(tape) | |
#println(index) | |
typeof(tape[index]) == Acc && continue | |
new_tape = deepcopy(tape) | |
if typeof(tape[index]) == Jmp | |
new_tape[index] = Nop(tape[index].value) | |
elseif typeof(tape[index]) == Nop | |
new_tape[index] = Jmp(tape[index].value) | |
end | |
accum,finished = execute_tape(new_tape) | |
if finished | |
return accum | |
end | |
end | |
end | |
d8p2("input_8.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment