mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
More improvements, because lua can do some things:
- Remove manual bookkeeping of array size - Remove duplicate 'snd' instruction - Instructions start at 1 now, I guess
This commit is contained in:
@@ -14,15 +14,11 @@ function split(input, match)
|
||||
end
|
||||
|
||||
instructions = {}
|
||||
icount = 0
|
||||
|
||||
while true do
|
||||
line = io.read()
|
||||
|
||||
if line == nil then break end
|
||||
|
||||
instructions[icount] = split(line, "%S+")
|
||||
icount = icount + 1
|
||||
table.insert(instructions, split(line, "%S+"))
|
||||
end
|
||||
|
||||
registers = {}
|
||||
@@ -41,8 +37,6 @@ function alu(instr, registers)
|
||||
-- Perform instruction and return offset to iptr
|
||||
if instr[1] == "set" then
|
||||
registers[instr[2]] = argval(instr[3], registers)
|
||||
elseif instr[1] == "snd" then
|
||||
last_played = argval(instr[2], registers)
|
||||
elseif instr[1] == "add" then
|
||||
registers[instr[2]] = argval(instr[2], registers) + argval(instr[3], registers)
|
||||
elseif instr[1] == "mul" then
|
||||
@@ -61,29 +55,25 @@ function alu(instr, registers)
|
||||
return 1
|
||||
end
|
||||
|
||||
iptr = 0
|
||||
iptr = 1
|
||||
|
||||
while true do
|
||||
while instructions[iptr][1] ~= "rcv" do
|
||||
instr = instructions[iptr]
|
||||
|
||||
if instr[1] == "snd" then
|
||||
last_played = argval(instr[2], registers)
|
||||
iptr = iptr + 1
|
||||
elseif instr[1] == "rcv" then
|
||||
print("Last played", last_played)
|
||||
iptr = iptr + 1
|
||||
break
|
||||
else
|
||||
iptr = iptr + alu(instr, registers)
|
||||
end
|
||||
end
|
||||
print("Last played", last_played)
|
||||
|
||||
registers = {{p=0}, {p=1}}
|
||||
|
||||
iptr = {0, 0} -- instruction pointers
|
||||
iptr = {1, 1} -- instruction pointers
|
||||
rbuf = {{}, {}} -- receive buffers
|
||||
rptr = {0, 0} -- Pointer in the receive buffer
|
||||
rctr = {0, 0} -- Number of entries in each buffer
|
||||
rptr = {1, 1} -- Pointer in the receive buffer
|
||||
waiting = {false, false} -- Whether one thread is waiting
|
||||
|
||||
pid = 1
|
||||
@@ -96,18 +86,12 @@ function nextpid(pid)
|
||||
end
|
||||
end
|
||||
|
||||
while true do
|
||||
while not waiting[pid] do
|
||||
instr = instructions[iptr[pid]]
|
||||
|
||||
if waiting[pid] then
|
||||
print("Deadlocked!")
|
||||
break
|
||||
end
|
||||
|
||||
if instr[1] == "snd" then
|
||||
npid = nextpid(pid)
|
||||
rbuf[npid][rctr[npid]] = argval(instr[2], registers[pid])
|
||||
rctr[npid] = rctr[npid] + 1
|
||||
table.insert(rbuf[npid], argval(instr[2], registers[pid]))
|
||||
waiting[npid] = false
|
||||
|
||||
iptr[pid] = iptr[pid] + 1
|
||||
@@ -127,4 +111,4 @@ while true do
|
||||
end
|
||||
|
||||
end
|
||||
print("Final sends from 1:", rctr[1])
|
||||
print("Final sends from 1:", #rbuf[1])
|
||||
|
||||
Reference in New Issue
Block a user