Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require("utils")
- local intcode = getinput()
- local processes = {}
- local function Process(intcode)
- local memory = parsecommas(intcode, tonumber)
- memory[0] = table.remove(memory, 1)
- setmetatable(memory, {
- __index = function(t, k)
- rawset(t, k, 0)
- return 0
- end;
- })
- local self = {
- memory = memory;
- ip = 0; -- instruction pointer
- pid = #processes + 1; -- process id
- input = {}; -- input queue
- output = nil; -- last output
- exit = false;
- relativeBase = 0;
- }
- processes[self.pid] = self
- return self
- end
- local process
- local operations = {
- [1]={3, true, function(a, b) return a + b end};
- [2]={3, true, function(a, b) return a * b end};
- [3]={1, true, function() return table.remove(process.input, 1) end};
- [4]={1, false, function(x) print(x) process.output = x end};
- [5]={2, false, function(a, b) if a ~= 0 then process.ip = b end end};
- [6]={2, false, function(a, b) if a == 0 then process.ip = b end end};
- [7]={3, true, function(a, b) return a < b and 1 or 0 end};
- [8]={3, true, function(a, b) return a == b and 1 or 0 end};
- [9]={1, false, function(x) process.relativeBase = process.relativeBase + x end};
- [99]={0, false, function() process.exit = true end}
- }
- local new = Process(intcode)
- table.insert(new.input, 2)
- process = processes[1]
- while true do
- local memory = process.memory
- local opcode = memory[process.ip]%100
- local operation = operations[opcode]
- local paramCount = operation[1]
- local writes = operation[2]
- local args = {}
- for i = 1, paramCount do
- local mode = memory[process.ip]//10^(i+1)%10
- local value = mode == 1 and (process.ip + i) or memory[process.ip + i]
- if mode == 2 then value = value + process.relativeBase end
- args[i] = (writes and i == paramCount) and value or memory[value]
- end
- local lastip = process.ip
- local result = operation[3](table.unpack(args))
- if process.exit then break end
- if writes then -- writes to
- memory[args[#args]] = result
- end
- if lastip == process.ip then -- didn't jump
- process.ip = process.ip + paramCount + 1
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement