Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. require("utils")
  2.  
  3. local intcode = getinput()
  4.  
  5. local processes = {}
  6. local function Process(intcode)
  7.     local memory = parsecommas(intcode, tonumber)
  8.     memory[0] = table.remove(memory, 1)
  9.     setmetatable(memory, {
  10.         __index = function(t, k)
  11.             rawset(t, k, 0)
  12.             return 0
  13.         end;
  14.     })
  15.     local self = {
  16.         memory = memory;
  17.         ip = 0; -- instruction pointer
  18.         pid = #processes + 1; -- process id
  19.         input = {}; -- input queue
  20.         output = nil; -- last output
  21.         exit = false;
  22.         relativeBase = 0;
  23.     }
  24.     processes[self.pid] = self
  25.     return self
  26. end
  27.  
  28. local process
  29. local operations = {
  30.     [1]={3, true, function(a, b) return a + b end};
  31.     [2]={3, true, function(a, b) return a * b end};
  32.     [3]={1, true, function() return table.remove(process.input, 1) end};
  33.     [4]={1, false, function(x) print(x) process.output = x end};
  34.     [5]={2, false, function(a, b) if a ~= 0 then process.ip = b end end};
  35.     [6]={2, false, function(a, b) if a == 0 then process.ip = b end end};
  36.     [7]={3, true, function(a, b) return a < b and 1 or 0 end};
  37.     [8]={3, true, function(a, b) return a == b and 1 or 0 end};
  38.     [9]={1, false, function(x) process.relativeBase = process.relativeBase + x end};
  39.     [99]={0, false, function() process.exit = true end}
  40. }
  41.  
  42. local new = Process(intcode)
  43. table.insert(new.input, 2)
  44. process = processes[1]
  45.  
  46. while true do
  47.     local memory = process.memory
  48.     local opcode = memory[process.ip]%100
  49.     local operation = operations[opcode]
  50.    
  51.     local paramCount = operation[1]
  52.     local writes = operation[2]
  53.     local args = {}
  54.     for i = 1, paramCount do
  55.         local mode = memory[process.ip]//10^(i+1)%10
  56.         local value = mode == 1 and (process.ip + i) or memory[process.ip + i]
  57.         if mode == 2 then value = value + process.relativeBase end
  58.         args[i] = (writes and i == paramCount) and value or memory[value]
  59.     end
  60.    
  61.     local lastip = process.ip
  62.     local result = operation[3](table.unpack(args))
  63.     if process.exit then break end
  64.     if writes then -- writes to
  65.         memory[args[#args]] = result
  66.     end
  67.     if lastip == process.ip then -- didn't jump
  68.         process.ip = process.ip + paramCount + 1
  69.     end
  70. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement