1
0
Fork 0

2020 day 8

This commit is contained in:
Lucidiot 2020-12-08 06:45:42 +01:00
parent 6dd88bf923
commit b1d71fe692
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
2 changed files with 67 additions and 1 deletions

66
2020/8/day8.lua Normal file
View File

@ -0,0 +1,66 @@
local commands = {}
for line in io.lines() do
local name, arg = line:match('^(%l+) ([+-]%d+)$')
local intarg = tonumber(arg:gsub('%+', ''), 10)
table.insert(commands, {name=name, arg=intarg, ran=false})
end
local function nop_cmd(arg, acc, pos)
return acc, pos + 1
end
local function acc_cmd(arg, acc, pos)
return acc + arg, pos + 1
end
local function jmp_cmd(arg, acc, pos)
return acc, pos + arg
end
local functions = {
nop=nop_cmd,
acc=acc_cmd,
jmp=jmp_cmd,
}
local function reset()
for _, command in ipairs(commands) do
command.ran = false
end
end
--[[
This function runs the program and returns two values:
- true if the program ends because of its last instruction
- false if the program ends because a command was already ran
--]]
local function run()
local acc, pos = 0, 1
while true do
if pos > #commands then
return true, acc
end
local command = commands[pos]
if command.ran then
return false, acc
end
acc, pos = functions[command.name](command.arg, acc, pos)
command.ran = true
end
end
-- Part 1
print(select(2, run()))
-- Part 2
for i, command in ipairs(commands) do
if (command.name == "nop" or command.name == "jmp") and command.arg ~= 0 then
command.name = command.name == "nop" and "jmp" or "nop"
reset()
local ended, acc = run()
if ended then
print(acc)
return
end
command.name = command.name == "nop" and "jmp" or "nop"
end
end

View File

@ -13,7 +13,7 @@ My solutions to the Advent of Code puzzles.
5 ██ ██ ██ ██
6 ██ ██ ██
7 ██ ██ ██
8 ██ ██
8 ██ ██ ██
9 ██
10 ██ ██
11 ██ ██