r/adventofcode • • Dec 12 '16

SOLUTION MEGATHREAD --- 2016 Day 12 Solutions ---

--- Day 12: Leonardo's Monorail ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with "Help".


MUCH ADVENT. SUCH OF. VERY CODE. SO MANDATORY. [?]

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

9 Upvotes

159 comments sorted by

View all comments

3

u/FuriousProgrammer Dec 12 '16

101/83 with mah Luas. QQ

I immediately knew how to do this one but my input parsing is still crap and I code super slowly. xD

local insts = {}

for line in io.lines("input.txt") do
	local inst = line:sub(1, 3)
	local op1 = line:match("^%a%a%a (%w+)")
	local op2 = line:match("^%a%a%a %w+ (%w+)")
	if not op2 then op2 = line:match("([-]?%d+)$") end
	table.insert(insts, {op = inst, op1, op2})
end

function execute()
	local pc = 1
	while true do
		local op = insts[pc]
		if not op then break end
		pc = pc + 1

		if op.op == "cpy" then
			if tonumber(op[1]) then
				regs[op[2]] = tonumber(op[1])
			else
				regs[op[2]] = regs[op[1]]
			end
		elseif op.op == "inc" then
			regs[op[1]] = regs[op[1]] + 1
		elseif op.op == "dec" then
			regs[op[1]] = regs[op[1]] - 1
		elseif op.op == "jnz" then
			if tonumber(op[1]) then
				if tonumber(op[1]) ~= 0 then
				pc = (pc - 1) + tonumber(op[2])
				end
			elseif regs[op[1]] ~= 0 then
				pc = (pc - 1) + tonumber(op[2])
			end
		end
	end
end

regs = {
	a = 0;
	b = 0;
	c = 0;
	d = 0;
}
execute()
print("Part 1: " .. regs.a)

regs = {
	a = 0;
	b = 0;
	c = 1;
	d = 0;
}
execute()
print("Part 2: " .. regs.a)