Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "importutils"
- local input_p = getInput(5):split(",", true)
- local dict =
- {
- id_1 = {fn = "add", params = 3},
- id_2 = {fn = "mult", params = 3},
- id_3 = {fn = "in", params = 1},
- id_4 = {fn = "out", params = 1},
- id_99 = {fn = "halt", params = 0},
- }
- local seed = 1 -- starting input
- local output = 0
- local function operate(input, id, params)
- local fn = dict[id].fn
- assert(fn == "halt" or (params and #params > 0), "No parameters passed for operation : "..fn)
- if fn == "out" then -- edge case
- if params[1].mode == 0 then params[1].val = input[params[1].val+1] end
- else
- for i=1, #params-1 do -- skip last since we want to keep the write address
- if params[i].mode == 0 then params[i].val = input[params[i].val+1] end
- end
- end
- if fn == "add" then return params[1].val + params[2].val, params[3].val
- elseif fn == "mult" then return params[1].val * params[2].val, params[3].val
- elseif fn == "in" then return seed, params[1].val
- elseif fn == "out" then return params[1].val, "out"
- elseif fn == "halt" then return "halt" end
- end
- local p = 1 -- input address pointer
- function runIntcodeComp(input)
- assert(type(input) == "table", "Input is not a table. Must pass a parsed table as input.")
- while p < #input do
- local opcode, parse = input[p]
- local id = string.format("id_%d", math.floor(string.sub(opcode, -2))) --shaves off leading 0 if exists
- local params = {}
- if #tostring(opcode) > 2 then
- parse = tostring(opcode):splitByChar()
- end
- assert(dict[id], "Invalid operation : "..id.." @ entry "..p)
- for i=1, dict[id].params do
- local t = {val=input[p+i], mode=0}
- if parse and parse[#parse-(i+1)] == "1" then t.mode = 1 end
- params[#params+1] = t
- end
- local result, pos = operate(input, id, params)
- if result == "halt" then
- print("Halt function has been pushed.")
- break
- end
- if pos == "out" then
- output = result
- print("Output is set to : "..output)
- else input[pos+1] = result end
- p = p + #params + 1
- end
- end
- runIntcodeComp(input_p)
- print("\nOutput is : "..output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement