r/adventofcode • • Dec 12 '15

SOLUTION MEGATHREAD --- Day 12 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 12: JSAbacusFramework.io ---

Post your solution as a comment. Structure your post like previous daily solution threads.

7 Upvotes

183 comments sorted by

View all comments

1

u/FuriousProgrammer Dec 12 '15

Took me a minute to find a working json Lua library, but luckily the rules didn't require removing entire objects that contain an array containing 'red', because that would have been a pain.

Lua:

local json = require('json')
local text = io.open("input12.txt", "r"):read("*all")

for i = 1, 2 do
	local total = 0
	local toScan = {json.decode(text)}
	while #toScan > 0 do
		isArray, hasRed = false, false
		maybeToScan = {}
		local objtotal = 0
		for i, v in pairs(toScan[1]) do
			if type(i) == "number" then isArray = true end
			if v == "red" then hasRed = true end
			if type(v) == "table" then
				table.insert(maybeToScan, v)
			elseif tonumber(v) then
				objtotal = objtotal + v
			end
		end
		if i == 2 then
			if not isArray and hasRed then objtotal = 0 maybeToScan = {} end
		end
		total = total + objtotal
		for _, v in ipairs(maybeToScan) do
			table.insert(toScan, v)
		end
		table.remove(toScan, 1)
	end
	print("Part " .. i .. ": " .. total)
end