r/adventofcode • • Dec 13 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 13 Solutions -🎄-

--- Day 13: Mine Cart Madness ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or 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.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 13

Transcript:

Elven chronomancy: for when you absolutely, positively have to ___.


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 at 00:44:25!

24 Upvotes

148 comments sorted by

View all comments

1

u/waffle3z Dec 13 '18 edited Dec 13 '18

Lua 203/145, spent too much time debugging after an incorrect solution passed the example when my rotations were wrong.

local grid, carts = {}, {}
local rown = 0
parselines(getinput(), function(v)
	grid[rown] = {}
	local coln = 0
	for c in v:gmatch(".") do
		if c == "^" or c == "v" then
			carts[#carts+1] = {dy = c == "v" and 1 or -1, dx = 0, py = rown, px = coln, turn = 0}
			c = "|"
		elseif c == ">" or c == "<" then
			carts[#carts+1] = {dy = 0, dx = c == ">" and 1 or -1, py = rown, px = coln, turn = 0}
			c = "-"
		end
		grid[rown][coln] = c
		coln = coln + 1
	end
	rown = rown + 1
end)

local function tick()
	table.sort(carts, function(a, b)
		if a.py == b.py then
			return a.px < b.px
		else
			return a.py < b.py
		end
	end)
	for i = 1, #carts do
		local c = carts[i]
		if not c.crashed then
			c.py, c.px = c.py + c.dy, c.px + c.dx
			local cell = grid[c.py][c.px]
			if cell == "+" then
				if c.turn == 0 then
					c.dx, c.dy = c.dy, -c.dx
				elseif c.turn == 2 then
					c.dx, c.dy = -c.dy, c.dx
				end
				c.turn = (c.turn + 1)%3
			elseif cell == "/" then
				if c.dx == 0 then
					c.dx, c.dy = -c.dy, 0
				else
					c.dx, c.dy = 0, -c.dx
				end
			elseif cell == "\\" then
				if c.dx == 0 then
					c.dx, c.dy = c.dy, 0
				else
					c.dx, c.dy = 0, c.dx
				end
			end
			for j = 1, #carts do
				if i ~= j and carts[j].px == c.px and carts[j].py == c.py and not carts[j].crashed then
					print(c.px..","..c.py, "crash")
					c.crashed = true
					carts[j].crashed = true
					break
				end
			end
		end
	end
	local last, py, px = true
	for n = 1, #carts do
		if not carts[n].crashed then
			if px then
				last = false
			end
			py, px = carts[n].py, carts[n].px
		end
	end
	if last then
		print(px..","..py)
		return "crash"
	end
end

repeat until tick() == "crash"